Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm using this code to process a file upload to a web api:

[HttpPost]
public async Task<IHttpActionResult> Post(string provider)
{  
    if (!Request.Content.IsMimeMultipartContent())
        throw new Exception();

    var streamProvider = new MultipartMemoryStreamProvider();
    await Request.Content.ReadAsMultipartAsync(streamProvider); // FAILS HERE
    foreach (var file in streamProvider.Contents)
    {
        var imageFilename = file.Headers.ContentDisposition.FileName.Trim('\"');
        var imageStream = await file.ReadAsStreamAsync();

    }
}

but it throws an error here: await Request.Content.ReadAsMultipartAsync(streamProvider);

The error is: Error reading MIME multipart body part. The inner Exception is:

{"Cannot access a disposed object."}

any ideas on why this error is coming up?

share|improve this question
    
better add try catch blocks –  user3629247 Jun 5 at 18:35
    
@user3629247 He has the exception already why would he need a trycatch? he wouldnt be posting here if he was ignoring the problem –  Tascalator Jun 5 at 18:39
    
@user441365 are you using the right Content-Type header value?? aka Content-Type: multipart/form-data –  Tascalator Jun 5 at 18:40
    
if we wrap our method in try-catch block,we can gracefully handle any errors that occur as part of the method. for this scenario he already catch the exception –  user3629247 Jun 5 at 18:42
    
Are you using the enctype attribute? –  djikay Jul 5 at 1:54
add comment

2 Answers 2

up vote 0 down vote accepted

Have you tried this?

[HttpPost]
public async Task<IHttpActionResult> Post(string provider)
{  
    if (!Request.Content.IsMimeMultipartContent())
        throw new Exception();

    var streamProvider = await Request.Content.ReadAsMultipartAsync(); // HERE
    foreach (var file in streamProvider.Contents)
    {
        var imageFilename = file.Headers.ContentDisposition.FileName.Trim('\"');
        var imageStream = await file.ReadAsStreamAsync();
    }
}

It looks as it should be called like this.

share|improve this answer
add comment

Shouldn't you have path to store uploaded files. Something like this:

var streamProvider = new MultipartMemoryStreamProvider(@"C:\Uploads");
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.