2013年10月11日 星期五

使用 Jersey + Multi-part 接受檔案上傳

基本參考對象是 [6] 的範例,因為 Jersey 基本上已經做完大部分的事情,所以程式碼其實很簡單
不過在佈署 Jersey 時可能會有一些奇怪的問題~

基本的 Multi-Part 的程式碼如下:
@POST
@Path("/upload_file")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFileByMultiPart (@FormDataParam("file") InputStream stream) {
  return uploadFile(headers, getParams, stream);
}
其中第四行 FormDataParam 的 anotation 就是 Jersey 自動幫忙解譯完 Multi-Part 後取得的內容
file 指的是網頁在做 form post 時,對應的那個 input 欄位的 name。

而關於伺服器方面,首先是 eclipse 跟佈署環境上,除了 Jersey 原本需要的 jersey-bundle 以外,還需要 multi-part 相關的函式庫
也就是 jersey-multipart.jar 跟 mimepull.jar 兩個 jar [7]。
另外必須要注意的是,jersey-bundle 的版本必須跟 jersey-multipart 的版本完全一致,否則佈署時會跑出類似下面的錯誤訊息 [8-9]。
SEVERE: Missing dependency for method public javax.ws.rs.core.Response Service.uploadFileByMultiPart(javax.ws.rs.core.HttpHeaders,javax.ws.rs.core.UriInfo,java.io.InputStream) at parameter at index 2
  SEVERE: Method, public javax.ws.rs.core.Response Service.uploadFileByMultiPart(javax.ws.rs.core.HttpHeaders,javax.ws.rs.core.UriInfo,java.io.InputStream), annotated with POST of resource, class Service, is not recognized as valid resource method.

如果想要一口氣拿一堆 MultiPart 的結果出來的話,可以參考 [10] 的方法,用 FormDataMultiPart 來取代 @FormDataParam。

參考資料:
1、How to return a PNG image from Jersey REST service method to the browser
2、RESTFul Webservice: File Upload with Jersey
3、[JERSEY] MULTIPART RESPONSES
4、Building jersey-multipart responses
5、[.NET] 產生具有多個值,multipart/form-data 的 HTTP POST 訊息
6、RESTFul Webservice: File Upload with Jersey
7、Exception :com.sun.jersey.spi.inject.Errors$ErrorMessagesException
8、Missing dependency for method when doing a file upload rest web service
9、Cannot implement simple file upload in Jersey - “annotated with POST of resource, class is not recognized as valid resource method. unavailable”
10、How to read several (file) inputs with the same name from a multipart form with Jersey?

沒有留言: