2017-07-03 53 views
0

我有一個WebAPI 2.1服務(ASP.Net MVC 4),接收和圖像及相關數據。 我需要從WPF應用程序發送此圖像,但我得到404未找到錯誤。c#發送圖像從WPF到WebAPI

服務器端

[HttpPost] 
[Route("api/StoreImage")] 
public string StoreImage(string id, string tr, string image) 
{ 
    // Store image on server... 
    return "OK"; 
} 

客戶端

public bool SendData(decimal id, int time, byte[] image) 
{ 
    string url = "http://localhost:12345/api/StoreImage"; 
    var wc = new WebClient(); 
    wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); 
    var parameters = new NameValueCollection() 
    { 
     { "id", id.ToString() }, 
     { "tr", time.ToString() }, 
     { "image", Convert.ToBase64String(image) } 
    }; 
    var res=wc.UploadValues(url, "POST", parameters); 
    return true; 
} 

的網址存在,我的事情,我需要編碼爲JSON格式,但我不知道怎麼辦。

謝謝你的時間!

+1

選中[在C#轉換對象JSON(https://stackoverflow.com/questions/11345382/convert-object-to-json-string-in- c-sharp) –

+0

已確定屬性路由已啓用?我也建議使用模型(DTO)來管理數據 – Nkosi

回答

1

您的案例中的方法參數以QueryString的形式收到。

我建議你把參數列表爲一個單一的對象是這樣的:

public class PhotoUploadRequest 
{ 
    public string id; 
    public string tr; 
    public string image; 
} 

然後你API中的字符串轉換從Base64String這樣的緩衝:

var buffer = Convert.FromBase64String(request.image); 

然後將其丟到HttpPostedFileBase

HttpPostedFileBase objFile = (HttpPostedFileBase)new MemoryPostedFile(buffer); 

現在你有圖像文件。做你想做的。

全部代碼在這裏:

[HttpPost] 
    [Route("api/StoreImage")] 
    public string StoreImage(PhotoUploadRequest request) 
    { 
     var buffer = Convert.FromBase64String(request.image); 
     HttpPostedFileBase objFile = (HttpPostedFileBase)new MemoryPostedFile(buffer); 
     //Do whatever you want with filename and its binaray data. 
     try 
     { 

      if (objFile != null && objFile.ContentLength > 0) 
      { 
       string path = "Set your desired path and file name"; 

       objFile.SaveAs(path); 

       //Don't Forget to save path to DB 
      } 

     } 
     catch (Exception ex) 
     { 
      //HANDLE EXCEPTION 
     } 

     return "OK"; 
    } 
+0

感謝@Ramy,它的工作原理! – Duefectu

+0

不客氣^ _ ^! @Duefectu –