2015-12-16 533 views
4

我試圖通過REST API將文件發送到服務器。該文件可能具有任何類型,但它的大小和類型可以限制爲可作爲電子郵件附件發送的內容。如何通過REST API發送文件?

我認爲我的做法是將文件作爲二進制流發送,然後在文件到達服務器時將其保存迴文件。有沒有內置的方式來在.Net中做到這一點,或者我需要手動將文件內容轉換爲數據流併發送?

爲了清楚起見,我可以控制客戶端和服務器代碼,所以我不受限於任何特定的方法。

+0

什麼_「將文件序列化爲二進制」_是什麼意思?所有文件都已經二進制。你在問什麼_exactly_?參見[如何接受文件POST - ASP.Net MVC 4 WebAPI](http://stackoverflow.com/questions/10320232/how-to-accept-a-file-post-asp-net-mvc-4-webapi )爲一些起點。 – CodeCaster

+0

你是對的,序列化是討論它的錯誤方式,我的意思是我需要直接發送二進制數據流,或使用不同的工具發送給我。我澄清了這個問題,@ MutantNinjaCodeMonkey的答案是我需要的 –

回答

4

我建議你看看RestSharp
http://restsharp.org/

RestSharp庫具有將文件發佈到REST服務的方法。 (RestRequst.AddFile())。我相信在服務器端,這會將編碼字符串轉換成正文,頭文件中的內容類型指定文件類型。

我也看到它通過將流轉換爲base-64字符串並將其作爲序列化的json/xml對象的屬性之一進行傳輸。特別是如果您可以設置大小限制並希望將請求中的文件元數據作爲同一對象的一部分包含在內,那麼這非常有效。

它確實取決於你的文件有多大。如果它們非常大,你需要考慮流式傳輸,其中的細微差別在這篇SO文章中有詳細介紹:How do streaming resources fit within the RESTful paradigm?

+0

這正是我所需要的,這要歸功於正確的方向。 –

0
  1. 檢測與請求一起傳輸的文件。
  2. 確定該文件將被上傳的路徑上(並確保CHMOD 777存在此目錄)
  3. 接受客戶端連接
  4. 使用現成庫實際上傳

審查以下討論: REST file upload with HttpRequestMessage or Stream?

+0

我不知道你的意思是數字4。「使用現成的圖書館」是什麼意思?我會研究另一個問題,當我在前面尋找答案時,我沒有看到。 –

+0

有幾個現成的開箱即用的庫,用於在.NET中上傳文件 其中有幾個是: https://msdn.microsoft.com/en-us/library/system.web.ui .webcontrols.fileupload(v = vs.110).aspx https://www.nuget.org/packages/AjaxUploader/ –

0

您可以將它作爲POST請求發送到服務器,將文件作爲FormParam傳遞。

@POST 
     @Path("/upload") 
     //@Consumes(MediaType.MULTIPART_FORM_DATA) 
     @Consumes("application/x-www-form-urlencoded") 
     public Response uploadFile(@FormParam("uploadFile") String script, @HeaderParam("X-Auth-Token") String STtoken, @Context HttpHeaders hh) { 

      // local variables 
      String uploadFilePath = null; 
      InputStream fileInputStream = new ByteArrayInputStream(script.getBytes(StandardCharsets.UTF_8)); 

      //System.out.println(script); //debugging 

      try { 
        uploadFilePath = writeToFileServer(fileInputStream, SCRIPT_FILENAME); 
      } 
      catch(IOException ioe){ 
       ioe.printStackTrace(); 
      } 
      return Response.ok("File successfully uploaded at " + uploadFilePath + "\n").build(); 
     } 

private String writeToFileServer(InputStream inputStream, String fileName) throws IOException { 

     OutputStream outputStream = null; 
     String qualifiedUploadFilePath = SIMULATION_RESULTS_PATH + fileName; 

     try { 
      outputStream = new FileOutputStream(new File(qualifiedUploadFilePath)); 
      int read = 0; 
      byte[] bytes = new byte[1024]; 
      while ((read = inputStream.read(bytes)) != -1) { 
       outputStream.write(bytes, 0, read); 
      } 
      outputStream.flush(); 
     } 
     catch (IOException ioe) { 
      ioe.printStackTrace(); 
     } 
     finally{ 
      //release resource, if any 
      outputStream.close(); 
     } 
     return qualifiedUploadFilePath; 
    } 
1

建立在@ MutantNinjaCodeMonkey的RestSharp建議。我的使用案例將來自jquery的$.ajax方法的webform數據發佈到web api控制器中。 restful API服務需要將上傳的文件添加到請求正文中。上面提到的AddFile的默認restsharp方法導致了錯誤The request was aborted: The request was canceled。下面的初始化工作:

// Stream comes from web api's HttpPostedFile.InputStream 
    (HttpContext.Current.Request.Files["fileUploadNameFromAjaxData"].InputStream) 
using (var ms = new MemoryStream()) 
{ 
    fileUploadStream.CopyTo(ms); 
    photoBytes = ms.ToArray(); 
} 

var request = new RestRequest(Method.PUT) 
{ 
    AlwaysMultipartFormData = true, 
    Files = { FileParameter.Create("file", photoBytes, "file") } 
};