简体   繁体   中英

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

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);
        }

}

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.

I solved this problem by doing this:

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

I was able to solve this issue by removing the headers I set manually on my post method. Angular 6 + .NET Web Api

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM