我将文件从客户端上传到网络api时遇到问题。我收到此错误“ MIME分段流意外结束。MIME分段消息不完整。”在控制器中,当我尝试读取多部分内容时。我正在用超级代理构建一个React JS客户端,这是我的请求代码:
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",
}
});
}
这是我的控制器代码:
[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);
}
}
最佳答案
我认为这里的问题是由于:
headers: {
"Content-Type": "multipart/form-data; boundary=gc0p4Jq0M2Yt08jU534c0p",
"Content-Disposition": "form-data; name=Foo",
}
我有一个类似的问题,并且通过删除标头参数得以解决,我猜是superagent自动添加了它们。