2014-02-07 34 views
3

我有我的API控制器中指定的所有表單數據的問題。具有多個文件到Web API控制器的自定義表單數據

JavaScript的上傳功能:

$scope.upload[index] = $upload.upload({ 
     url: '/api/upload/', 
     method: 'POST', 
     data: { 
      Photographer: $scope.models[index].photographer, 
      Description: $scope.models[index].desc 
     }, 
     file: $scope.models[index].file 
    }) 

表單數據: 工程,我想它,則發送它包含了我的價值觀,我想它的每個請求。

------WebKitFormBoundaryzlLjAnm449nw1EvC 
Content-Disposition: form-data; name="Photographer" 

Scott Johnson 
------WebKitFormBoundaryzlLjAnm449nw1EvC 
Content-Disposition: form-data; name="Description" 

Image taken with a Nikon camerea 
------WebKitFormBoundaryzlLjAnm449nw1EvC 
Content-Disposition: form-data; name="file"; filename="moxnes.jpg" 
Content-Type: image/jpeg 

我的Web API控制器:

模板從this guide

public class UploadController : ApiController 
{ 
    public async Task <HttpResponseMessage> PostFormData() 
    { 
     var root = HttpContext.Current.Server.MapPath("~/App_Data"); 
     var provider = new MultipartFormDataStreamProvider(root); 

     try 
     { 
      // Read the form data. 
      await Request.Content.ReadAsMultipartAsync(provider); 

      // Show all the key-value pairs. 
      foreach(var key in provider.FormData.AllKeys) 
      { 
       foreach(var val in provider.FormData.GetValues(key)) 
       { 
        var keyValue = string.Format("{0}: {1}", key, val); 
       } 
      } 

      foreach(MultipartFileData fileData in provider.FileData) 
      { 
       var fileName = fileData.Headers.ContentDisposition.FileName; 
      } 
      return Request.CreateResponse(HttpStatusCode.OK); 
     } 
     catch (Exception e) 
     { 
      return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e); 
     } 
    } 
} 

這裏的問題:控制器可以通過這個循環異步接收多個請求和讀取所有文件:foreach(MultipartFileData fileData in provider.FileData)這工作正常,但我的其他表單數據值(Phtographer和說明)只包含其中一個請求(收到的最後一個請求)的值。

foreach(var key in provider.FormData.AllKeys) 

我需要取出每個請求的表格數據值。我該怎麼做,或者有什麼更好的辦法來解決這個問題?也許通過添加模型作爲參數?

回答

2

我用這個具有角一起,它爲我工作得很好:

public partial class UploadController : ApiController 
{ 
    [HttpPost] 
    public Task<HttpResponseMessage> PostFormData() 
    { 
     // Check if the request contains multipart/form-data. 
     if (!Request.Content.IsMimeMultipartContent()) { 
      throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); 
     } 

     string root = HttpContext.Current.Server.MapPath("~/App_Data"); 
     var provider = new MultipartFormDataStreamProvider(root); 

     // Read the form data and return an async task. 
     var task = Request.Content.ReadAsMultipartAsync(provider). 
      ContinueWith<HttpResponseMessage>(t => 
      { 
       if (t.IsFaulted || t.IsCanceled) { 
        Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception); 
       } 


       foreach (MultipartFileData file in provider.FileData) { 
        using (StreamReader fileStream = new StreamReader(file.LocalFileName)){ 
         if (provider.FormData.AllKeys.AsParallel().Contains("demo")){ 
          //read demo key value from form data successfully 
         } 
         else{ 
          //failed to read demo key value from form. 
         } 
        } 
       } 
       return Request.CreateResponse(HttpStatusCode.OK, "OK"); 
      }); 

     return task; 
    } 
... 
3

我創建了一個MediaTypeFormatter解碼多部分/表單數據,並通過模型結合提供了一個HttpPostedFileBase。它使文件上傳與任何其他API參數一樣簡單。它目前加載完整的文件上傳到內存,但格式化程序可以很容易地調整,以將上傳的數據寫入臨時上傳目錄。

https://gist.github.com/Danielku15/bfc568a19b9e58fd9e80

在API配置只需註冊格式化和你都設置在您的數據傳輸模型來使用它:

Configuration.Formatters.Add(new FormMultipartEncodedMediaTypeFormatter()); 
相關問題