2016-08-18 108 views
1

我在使用FormData API上传的网站中有一个canvas元素。下面是我如何做到这一点:ReadAsMultipartAsync如何实际工作?

upload: function (e) { 
    var file = this.imagePreview.ui.canvas.get(0).toDataURL("image/jpeg") 
        .replace('data:image/jpeg;base64,', ''); 
    if (file) { 
     var formData = new FormData(); 
     formData.append('file', file); 
     $.ajax({ 
      url: app.getApiRoot + 'UserFiles/', 
      type: "post", 
      data: formData, 
      processData: false, 
      contentType: false, 
      error: function() { 
       $("#file_upload_result").html('there was an error while submitting'); 
      } 
     }); 
    } 
} 

在那里我更换整个data:image/jpeg;base64,业务按this post

在后端我有以下多控制器:

public async Task<IHttpActionResult> PostUserFile() 
{ 
    string imageDir = ConfigurationManager.AppSettings["UploadedImageDir"]; 
    var PATH = HttpContext.Current.Server.MapPath("~/" + imageDir); 
    var rootUrl = Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.AbsolutePath, String.Empty); 

    if (Request.Content.IsMimeMultipartContent()) 
    { 
     var streamProvider = new CustomMultipartFormDataStreamProvider(PATH); 
     await Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t => 
     { 
      if (t.IsFaulted || t.IsCanceled) 
      { 
       throw new HttpResponseException(HttpStatusCode.InternalServerError); 
      } 

      var files = streamProvider.FileData.Select(i => 
         { 
          var info = new FileInfo(i.LocalFileName); 
          return new UserFile(User.Identity.GetUserId(), info.Name, rootUrl + "/" + imageDir + "/" + info.Name, info.Length/1024); 
         }); 

      db.UserFiles.AddRange(files); 
      db.SaveChangesAsync(); 
     }); 

     return Ok(); 
    } 
    else 
    { 
     throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted")); 
    } 
} 

我在哪里实现CustomMultipartFormDataStreamProvider如下:

public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider 
{ 
    public CustomMultipartFormDataStreamProvider(string path) 
     : base(path) 
    { } 

    public override string GetLocalFileName(Headers.HttpContentHeaders headers) 
    { 
     var name = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? 
         headers.ContentDisposition.FileName : 
         "NoName"; 
     // This is here because Chrome submits files in quotation 
     // marks which get treated as part of the filename and get escaped 
     return name.Replace("\"\"", string.Empty); 
    } 
} 

不幸的是,在供给到ReadAsMultipartAsync方法streamProviderFileData是空:

FileData count = 0

而且我觉得有趣的另一件事是,上传的二进制文件被转义,因为我从监视窗口中看到:

Escaped data

%2f对于/字符转义序列。

我简直不能查明问题。任何人有任何建议?

回答

0

混合ContinueWith和异步/等待会导致问题,只是做await Request.Content.ReadAsMultipartAsync(streamProvider);.ContinueWith的一切都会像正常代码一样在等待。

或者删除异步/等待并添加:

return Request.Content.ReadAsMultipartAsync(streamProvider).Continu‌​eWith... 

您也可以看看这个链接:Sending HTML Form Data in ASP.NET Web API: File Upload and Multipart MIME

+0

请解释回答更多的细节。 –

+0

请尝试学习如何使用Stackoverflow。编辑答案,不要在评论中添加信息。阅读此:https://stackoverflow.com/help/how-to-answer –

+0

听起来很合理。让我今天晚些时候实施它,并回到你身边。 – seebiscuit