7

我想通過附加表單數據上傳文件並通過MVC發佈到Web API,但是我無法完成。從附加表單數據到MVC的Web Api文件上傳

MVC邊

首先,我得到了提交的表單在MVC。這是對此的行動。

[HttpPost] 
      public async Task<ActionResult> Edit(BrandInfo entity) { 

       try { 
        byte[] logoData = null; 
        if(Request.Files.Count > 0) { 
         HttpPostedFileBase logo = Request.Files[0]; 
         logoData = new byte[logo.ContentLength]; 
         logo.InputStream.Read(logoData, 0, logo.ContentLength); 
         entity.Logo = logo.FileName; 
         entity = await _repo.Update(entity.BrandID, entity, logoData); 
        } 
        else 
         entity = await _repo.Update(entity,entity.BrandID); 
        return RedirectToAction("Index", "Brand"); 
       } 
       catch(HttpApiRequestException e) { 
// logging, etc     
        return RedirectToAction("Index", "Brand"); 
       } 
      } 

下面的代碼後的Multipartform對Web API

string requestUri = UriUtil.BuildRequestUri(_baseUri, uriTemplate, uriParameters: uriParameters); 
      MultipartFormDataContent formData = new MultipartFormDataContent(); 
      StreamContent streamContent = null; 
      streamContent = new StreamContent(new MemoryStream(byteData));    
      streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { 
       FileName = "\"" + fileName + "\"", 
       Name = "\"filename\"" 
      }; 
      streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); 
      formData.Add(streamContent); 
      formData.Add(new ObjectContent<TRequestModel>(requestModel, _writerMediaTypeFormatter), "entity"); 
      return _httpClient.PutAsync(requestUri, formData).GetHttpApiResponseAsync<TResult>(_formatters); 

正如你可以看到我試圖將文件發送數據和對象有相同MultipartFormDataContent。我找不到更好的方式發送我的實體ObjectContent。此外,我正在使用JSON.Net串行器

關於小提琴手,後似乎成功。

PUT http://localhost:12836/api/brand/updatewithlogo/13 HTTP/1.1 
Content-Type: multipart/form-data; boundary="10255239-d2a3-449d-8fad-2f31b1d00d2a" 
Host: localhost:12836 
Content-Length: 4341 
Expect: 100-continue 

--10255239-d2a3-449d-8fad-2f31b1d00d2a 
Content-Disposition: form-data; filename="web-host-logo.gif"; name="filename" 
Content-Type: application/octet-stream 

GIF89a��L������X�������wW����������xH�U�)�-�k6�������v6�������̥�v�J���������7����V:�=#�ի�I(�xf�$������� 
// byte data 
// byte data 
'pf�Y��y�ؙ�ڹ�(�; 
--10255239-d2a3-449d-8fad-2f31b1d00d2a 
Content-Type: application/json; charset=utf-8 
Content-Disposition: form-data; name=entity 

{"BrandID":13,"AssetType":null,"AssetTypeID":2,"Logo":"web-host-logo.gif","Name":"Geçici Brand","Models":null,"SupplierBrands":null} 
--10255239-d2a3-449d-8fad-2f31b1d00d2a-- 

的Web API邊

最後我正在追趕在後的Web API側,並試圖解析,但我不能。因爲MultipartFormDataStreamProviderFileDataFormData集合總是空的。

[HttpPut] 
     public void UpdateWithLogo(int id) { 
      if(Request.Content.IsMimeMultipartContent()) { 
       var x = 1; // this code has no sense, only here to check IsMimeMultipartContent 
      } 

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

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

       foreach(var key in provider.FormData.AllKeys) { 
        foreach(var val in provider.FormData.GetValues(key)) { 
         _logger.Info(string.Format("{0}: {1}", key, val)); 
        } 
       } 

       // This illustrates how to get the file names. 
       foreach(MultipartFileData file in provider.FileData) { 
        _logger.Info(file.Headers.ContentDisposition.FileName); 
        _logger.Info("Server file path: " + file.LocalFileName); 
       }    
      } 
      catch(Exception e) { 
       throw new HttpApiRequestException("Error", HttpStatusCode.InternalServerError, null); 
      }    
     } 

我希望你能幫我找到我的錯誤。

UPDATE

我也意識到,如果我註釋掉StreamContentObjectContent和只添加的StringContent,我仍然無法從MultipartFormDataStreamProvider得到任何東西。

+0

我遇到了一個稍微不同的問題 - 瀏覽器是從請求下降我的文件,直到我給他們的名稱/ ID。這對診斷問題有很大的幫助,雖然 – brichins 2015-11-02 18:47:56

回答

5

最後我解決我的問題,這是所有關於異步 :)

正如你可以在API操作方法見我呼籲ReadAsMultipartAsync方法synchrously但這是一個錯誤。我不得不用ContinueWith來調用它,所以在我改變我的代碼之後,我的問題就解決了。

var files = Request.Content.ReadAsMultipartAsync(provider).ContinueWith<HttpResponseMessage>(task => { 
        if(task.IsFaulted) 
         throw task.Exception; 
// do additional stuff 
}); 
+0

如果這解決了問題,請將其標記爲已接受。 – anaximander 2013-03-26 15:48:56

+0

啊,我忘了那個限制。 – anaximander 2013-03-26 15:57:20

+1

對不起,我在這裏有點困惑。什麼是完全的任務?我也應該在這裏處理表格數據嗎? – Bobby5193 2013-09-28 11:12:32

相關問題