星期二, 6月 07, 2011

[Java] Upload file using Jersey

目前使用Jersey接收上傳檔案只能使用HttpServletRequest來接收上傳成功!!
尚未解決使用@FormDataParam無法上傳的錯誤!!待解
 //目前會HTTP Status 415 - Unsupported Media Type大爆炸
 @POST
 @Path("/simpleupload2")
 @Consumes(MediaType.MULTIPART_FORM_DATA)
 public void simpleUpload2(
   @FormDataParam("username") final  String username,
   @FormDataParam("filedata") final  InputStream file,
   @FormDataParam("filedata") final  FormDataContentDisposition disposition){
  
  System.out.println("username:" + username);
 }

以下範例是使用Apache FileUpload Module 來取得上傳的檔案物件
@POST
 @Path("/simpleupload")
 @Consumes(MediaType.MULTIPART_FORM_DATA)
 public void simpleUpload(
   //@Context UriInfo ui,
   @Context HttpServletRequest request
  ){

  String fileRepository = "D:\\";
  if (ServletFileUpload.isMultipartContent(request)) {
   FileItemFactory factory = new DiskFileItemFactory();
   ServletFileUpload upload = new ServletFileUpload(factory);
   List<FileItem> items = null;
   try {
    items = upload.parseRequest(request);
   } catch (FileUploadException e) {
    e.printStackTrace();
   }
   if (items != null) {
    Iterator<FileItem> iter = items.iterator();
    while (iter.hasNext()) {
     FileItem item = iter.next();
     if (!item.isFormField() && item.getSize() > 0) {
      System.out.println("File is found.");
      String fileName = processFileName(item.getName());
      try {
       String savePath = fileRepository + fileName;
       System.out.println("savePath:" + savePath);
       item.write(new File(savePath));
      } catch (Exception e) {
       e.printStackTrace();
      }
     }else{
      System.out.println("getFieldName:" + item.getFieldName());
      System.out.println(item.getString());
     }
    }
   }
  }
 }

Reference:
Multiple file upload using RESTful web service (Jersey)

2 則留言:

  1. 其实问题貌似出在 FormDataContentDisposition 上,并且记得+上 mimepull.jar 在 buildpath 里面。 我还在找 FormDataContentDisposition 的问题到底出哪儿了。。

    回覆刪除

留個話吧:)

其他你感興趣的文章

Related Posts with Thumbnails