Unexpected end of MIME multipart stream. MIME multipart message is not complete. Web API and superagent

Andreas Jangefalk picture Andreas Jangefalk · Aug 24, 2016 · Viewed 12k times · Source

I have a problem with uploading files from client to web api. I am getting this error "Unexpected end of MIME multipart stream. MIME multipart message is not complete." in the controller when i am trying to read the multipart content. I ma building an React JS client with superagent and this is my code for the request:

 UploadFiles(files: File[]): Promise.IThenable<any> {

    return this.Post("/Payment/files" , {
        data: {
            files: files
        },
        headers: {
            "Content-Type": "multipart/form-data; boundary=gc0p4Jq0M2Yt08jU534c0p",
            "Content-Disposition": "form-data; name=Foo",
        }
    });
}

And this is my controller code:

[Route("files")]
[HttpPost]
public async Task<HttpResponseMessage> UploadFiles()
{
        string root = Path.GetTempPath();
        var provider = new MultipartFormDataStreamProvider(root);

        Stream reqStream = Request.Content.ReadAsStreamAsync().Result;
        MemoryStream tempStream = new MemoryStream();
        reqStream.CopyTo(tempStream);

        tempStream.Seek(0, SeekOrigin.End);
        StreamWriter writer = new StreamWriter(tempStream);
        writer.WriteLine();
        writer.Flush();
        tempStream.Position = 0;

        StreamContent streamContent = new StreamContent(tempStream);
        foreach (var header in Request.Content.Headers)
        {
            streamContent.Headers.Add(header.Key, header.Value);

        }
        try
        {
            // Read the form data.
            streamContent.LoadIntoBufferAsync().Wait();

            //This is where it bugs out
            await streamContent.ReadAsMultipartAsync(provider);


            return Request.CreateResponse(HttpStatusCode.OK);
        }
        catch (Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        }

}

Answer

Stew picture Stew · Oct 17, 2016

I think the issue here is caused by:

headers: {
             "Content-Type": "multipart/form-data; boundary=gc0p4Jq0M2Yt08jU534c0p",
             "Content-Disposition": "form-data; name=Foo",
         }

I had a similar issue and was solved by removing the header parameters, am guessing that superagent adds them automatically.