我将如何去使用MultipartFormDataStreamProvider
和Request.Content.ReadAsMultipartAsync
在ApiController
?使用MultipartFormDataStreamProvider和ReadAsMultipartAsync
我GOOGLE了一些教程,但我不能让他们任何工作,即时通讯使用.net 4.5。
这是我目前得到:
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"));
}
}
}
我得到的异常MIME多流的
意外结束。 MIME多部分消息不是 完整。
当await task;
运行。 是否有任何人知道我在做什么错误或有一个正常的asp.net项目使用web API的工作示例。
如果't.IsFaulted'为true,则表示存在异常,并且将填充到Exception属性中。看看例外是什么。或者只是“等待任务;”来简化代码,除此之外,它将重新抛出任何异常。 – Servy
之后用“await任务”替换ContinueWith和if后的句子;我得到“意外的MIME多部分流结束。MIME多部分信息不完整。” – Peter
我觉得下面的帖子可能会帮助 http://stackoverflow.com/questions/17177237/webapi-ajax-formdata-upload-with-extra-parameters – user2880706