2012-12-05 43 views
16

我将如何去使用MultipartFormDataStreamProviderRequest.Content.ReadAsMultipartAsyncApiController使用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的工作示例。

+0

如果't.IsFaulted'为true,则表示存在异常,并且将填充到Exception属性中。看看例外是什么。或者只是“等待任务;”来简化代码,除此之外,它将重新抛出任何异常。 – Servy

+0

之后用“await任务”替换ContinueWith和if后的句子;我得到“意外的MIME多部分流结束。MIME多部分信息不完整。” – Peter

+0

我觉得下面的帖子可能会帮助 http://stackoverflow.com/questions/17177237/webapi-ajax-formdata-upload-with-extra-parameters – user2880706

回答

28

我解决了这个错误,我不明白这与多流的末尾做的,但这里是工作代码:

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"); 
     } 
    } 
} 
+2

我们可以看到这个帖子的方法是如何被调用的例子由客户? –

+0

我在'await'开始的行出现以下错误: “在HttpRequest.GetBufferedInputStream的调用者填充内部存储器之前,BinaryRead,Form,Files或InputStream被访问。 对于可能的原因,你有什么建议吗? – ciuncan

+0

@ciuncan检查答案http://stackoverflow.com/questions/17602845/post-error-either-binaryread-form-files-or-inputstream-was-accessed-before-t它可能会帮助你! – Peter

6

首先你应该确定ENCTYPE/ajax请求头中的表单数据。

[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; 
    } 
} 
相关问题