C# 使用 MultipartFormDataStreamProvider 和 ReadAsMultipartAsync
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13732766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
using MultipartFormDataStreamProvider and ReadAsMultipartAsync
提问by Peter
How would i go about using MultipartFormDataStreamProviderand Request.Content.ReadAsMultipartAsyncin a ApiController?
我将如何去使用MultipartFormDataStreamProvider和Request.Content.ReadAsMultipartAsync在ApiController?
I have googled a few tutorial but i can't get any of them to work, im using .net 4.5.
我在谷歌上搜索了一些教程,但我无法让其中任何一个工作,我使用的是 .net 4.5。
This is what i currently got:
这是我目前得到的:
public class TestController : ApiController
{
const string StoragePath = @"T:\WebApiTest";
public async void Post()
{
if (Request.Content.IsMimeMultipartContent())
{
var streamProvider = new MultipartFormDataStreamProvider(Path.Combine(StoragePath, "Upload"));
await Request.Content.ReadAsMultipartAsync(streamProvider);
foreach (MultipartFileData fileData in streamProvider.FileData)
{
if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName))
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
}
string fileName = fileData.Headers.ContentDisposition.FileName;
if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
{
fileName = fileName.Trim('"');
}
if (fileName.Contains(@"/") || fileName.Contains(@"\"))
{
fileName = Path.GetFileName(fileName);
}
File.Copy(fileData.LocalFileName, Path.Combine(StoragePath, fileName));
}
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
}
}
}
I get the exception
我得到了例外
Unexpected end of MIME multipart stream. MIME multipart message is not complete.
MIME 多部分流意外结束。MIME 多部分消息不完整。
when the await task;runs.
Does any one have any idea what i am doing wrong or have a working example in a normal asp.net project using web api.
当await task;运行。有没有人知道我做错了什么,或者在使用 web api 的普通 asp.net 项目中有一个工作示例。
采纳答案by Peter
I resolved the error, i don't understand what this has to do with end of multipart stream but here is the working code:
我解决了错误,我不明白这与多部分流结束有什么关系,但这是工作代码:
public class TestController : ApiController
{
const string StoragePath = @"T:\WebApiTest";
public async Task<HttpResponseMessage> Post()
{
if (Request.Content.IsMimeMultipartContent())
{
var streamProvider = new MultipartFormDataStreamProvider(Path.Combine(StoragePath, "Upload"));
await Request.Content.ReadAsMultipartAsync(streamProvider);
foreach (MultipartFileData fileData in streamProvider.FileData)
{
if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName))
{
return Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted");
}
string fileName = fileData.Headers.ContentDisposition.FileName;
if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
{
fileName = fileName.Trim('"');
}
if (fileName.Contains(@"/") || fileName.Contains(@"\"))
{
fileName = Path.GetFileName(fileName);
}
File.Move(fileData.LocalFileName, Path.Combine(StoragePath, fileName));
}
return Request.CreateResponse(HttpStatusCode.OK);
}
else
{
return Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted");
}
}
}
回答by Hamid
at first you should define enctypeto multipart/form-data in ajax request header.
首先,您应该在 ajax 请求标头中将enctype定义为multipart/form-data 。
[Route("{bulkRequestId:int:min(1)}/Permissions")]
[ResponseType(typeof(IEnumerable<Pair>))]
public async Task<IHttpActionResult> PutCertificatesAsync(int bulkRequestId)
{
if (Request.Content.IsMimeMultipartContent("form-data"))
{
string uploadPath = HttpContext.Current.Server.MapPath("~/uploads");
var streamProvider = new MyStreamProvider(uploadPath);
await Request.Content.ReadAsMultipartAsync(streamProvider);
List<Pair> messages = new List<Pair>();
foreach (var file in streamProvider.FileData)
{
FileInfo fi = new FileInfo(file.LocalFileName);
messages.Add(new Pair(fi.FullName, Guid.NewGuid()));
}
//if (_biz.SetCertificates(bulkRequestId, fileNames))
//{
return Ok(messages);
//}
//return NotFound();
}
return BadRequest();
}
}
public class MyStreamProvider : MultipartFormDataStreamProvider
{
public MyStreamProvider(string uploadPath) : base(uploadPath)
{
}
public override string GetLocalFileName(HttpContentHeaders headers)
{
string fileName = Guid.NewGuid().ToString()
+ Path.GetExtension(headers.ContentDisposition.FileName.Replace("\"", string.Empty));
return fileName;
}
}

