2013-11-27 34 views
4

我在嘗試從我的桌面應用程序上傳文件到遠程服務器。在瀏覽一段時間之後,這種方法似乎是最簡單的方法。問題是在服務器端沒有收到參數。我錯過了什麼?如何通過HttpClient PostAsync方法將文件和參數上傳到遠程服務器?

private void AddFile(FileInfo fileInfo, int folderId) 
    { 
     using (var handler = new HttpClientHandler() {CookieContainer = _cookies}) 
     { 
      using (var client = new HttpClient(handler) {BaseAddress = new Uri(_host)}) 
      { 
       var requestContent = new MultipartFormDataContent(); 
       var fileContent = new StreamContent(fileInfo.Open(FileMode.Open)); 
       var folderContent = new StringContent(folderId.ToString(CultureInfo.InvariantCulture)); 
       requestContent.Add(fileContent, "file", "file"); 
       requestContent.Add(folderContent, "folderId", "folderId"); 

       client.PostAsync("/Company/AddFile", requestContent); 
      } 
     } 
    } 

編輯:這是服務器端的期待簽名:

[HttpPost] 
    public ActionResult AddFile(HttpPostedFileBase file, int folderId) 
+0

服務器端簽名是MVC控制器中的Action嗎?你有控制它嗎? – SalvadorGomez

+0

它在MVC控制器中。目前我無法修改它。 – Billdr

+0

請給我們服務器的網站代碼。 – Teddy

回答

5

試驗和錯誤的很多我得到了它之後。有幾個問題。 1)參數名稱預計引號2)我錯過了一堆頭信息。這是工作代碼。

private void AddFile(FileInfo fileInfo, int folderId) 
    { 
     using (var handler = new HttpClientHandler() {CookieContainer = _cookies}) 
     { 
      using (var client = new HttpClient(handler) {BaseAddress = new Uri(_host)}) 
      { 
       var requestContent = new MultipartFormDataContent(); 
       var fileContent = new StreamContent(fileInfo.OpenRead()); 
       fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") 
        { 
         Name = "\"file\"", 
         FileName = "\"" + fileInfo.Name + "\"" 
        }; 
       fileContent.Headers.ContentType = 
        MediaTypeHeaderValue.Parse(MimeMapping.GetMimeMapping(fileInfo.Name)); 
       var folderContent = new StringContent(folderId.ToString(CultureInfo.InvariantCulture)); 

       requestContent.Add(fileContent); 
       requestContent.Add(folderContent, "\"folderId\""); 

       var result = client.PostAsync("Company/AddFile", requestContent).Result; 
      } 
     } 
相關問題