JAX-RS之上传文件

来源:互联网 发布:mac 触摸板 鼠标 消失 编辑:程序博客网 时间:2024/06/05 12:46
今天学习的是jax-rs中的上传文件.
1 首先要包含的是resteasy-multipart-provider.jar这个文件

2) 之后是简单的HTML FORM
   <html>
<body>
<h1>JAX-RS Upload Form</h1>

<form action="rest/file/upload" method="post" enctype="multipart/form-data">

  
Select a file : <input type="file" name="uploadedFile" size="50" />
  


   <input type="submit" value="Upload It" />
</form>

</body>
</html>

3 代码如下,先列出,再讲解:
  
Java代码 复制代码
  1.  import java.io.File;   
  2. import java.io.FileOutputStream;   
  3. import java.io.IOException;   
  4. import java.io.InputStream;   
  5. import java.util.List;   
  6. import java.util.Map;   
  7. import javax.ws.rs.Consumes;   
  8. import javax.ws.rs.POST;   
  9. import javax.ws.rs.Path;   
  10. import javax.ws.rs.core.MultivaluedMap;   
  11. import javax.ws.rs.core.Response;   
  12. import org.apache.commons.io.IOUtils;   
  13. import org.jboss.resteasy.plugins.providers.multipart.InputPart;   
  14. import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;   
  15.     
  16. @Path("/file")   
  17. public class UploadFileService {   
  18.     
  19.     private final String UPLOADED_FILE_PATH = "d:\\";   
  20.     
  21.     @POST  
  22.     @Path("/upload")   
  23.     @Consumes("multipart/form-data")   
  24.     public Response uploadFile(MultipartFormDataInput input) {   
  25.     
  26.         String fileName = "";   
  27.     
  28.         Map<String, List<InputPart>> uploadForm = input.getFormDataMap();   
  29.         List<InputPart> inputParts = uploadForm.get("uploadedFile");   
  30.     
  31.         for (InputPart inputPart : inputParts) {   
  32.     
  33.          try {   
  34.     
  35.             MultivaluedMap<String, String> header = inputPart.getHeaders();   
  36.             fileName = getFileName(header);   
  37.     
  38.             //convert the uploaded file to inputstream  
  39.             InputStream inputStream = inputPart.getBody(InputStream.class,null);   
  40.     
  41.             byte [] bytes = IOUtils.toByteArray(inputStream);   
  42.     
  43.             //constructs upload file path   
  44.             fileName = UPLOADED_FILE_PATH + fileName;   
  45.     
  46.             writeFile(bytes,fileName);   
  47.     
  48.             System.out.println("Done");   
  49.     
  50.           } catch (IOException e) {   
  51.             e.printStackTrace();   
  52.           }   
  53.     
  54.         }   
  55.     
  56.         return Response.status(200)   
  57.             .entity("uploadFile is called, Uploaded file name : " + fileName).build();   
  58.     
  59.     }   
  60.     
  61.     /**  
  62.      * header sample  
  63.      * {  
  64.      *  Content-Type=[image/png],   
  65.      *  Content-Disposition=[form-data; name="file"; filename="filename.extension"] 
  66.      * }  
  67.      **/  
  68.     //get uploaded filename, is there a easy way in RESTEasy?  
  69.     private String getFileName(MultivaluedMap<String, String> header) {   
  70.     
  71.         String[] contentDisposition = header.getFirst("Content-Disposition").split(";");   
  72.     
  73.         for (String filename : contentDisposition) {   
  74.             if ((filename.trim().startsWith("filename"))) {   
  75.     
  76.                 String[] name = filename.split("=");   
  77.     
  78.                 String finalFileName = name[1].trim().replaceAll("\"""");   
  79.                 return finalFileName;   
  80.             }   
  81.         }   
  82.         return "unknown";   
  83.     }   
  84.     
  85.     //save to somewhere   
  86.     private void writeFile(byte[] content, String filename) throws IOException {   
  87.     
  88.         File file = new File(filename);   
  89.     
  90.         if (!file.exists()) {   
  91.             file.createNewFile();   
  92.         }   
  93.     
  94.         FileOutputStream fop = new FileOutputStream(file);   
  95.     
  96.         fop.write(content);   
  97.         fop.flush();   
  98.         fop.close();   
  99.     
  100.     }   
  101. }  

   这里,用户选择了文件上传后,会URL根据REST的特性,自动map
到uploadFile方法中,然后通过:
   Map<String, List<InputPart>> uploadForm = input.getFormDataMap();

List<InputPart> inputParts = uploadForm.get("uploadedFile"); 
   找出所有的上传文件框(可以是多个),然后进行循环工作:
  首先是获得每个文件头的HEADER,用这个
MultivaluedMap<String, String> header = inputPart.getHeaders();
然后在header中取出文件名,这里使用的方法是getFileName,另外写了个方法:

 
Java代码 复制代码
  1.   private String getFileName(MultivaluedMap<String, String> header) {   
  2.   
  3.     String[] contentDisposition = header.getFirst("Content-Disposition").split(";");   
  4.   
  5.     for (String filename : contentDisposition) {   
  6.         if ((filename.trim().startsWith("filename"))) {   
  7.   
  8.             String[] name = filename.split("=");   
  9.   
  10.             String finalFileName = name[1].trim().replaceAll("\"""");   
  11.             return finalFileName;   
  12.         }   
  13.     }   
  14.     return "unknown";   
  15. }  


  这里,比较麻烦,要获得header,比如header是如下形式的,然后要再提取其中的文件名:
Content-Disposition=[form-data; name="file"; filename="filename.extension"]
   最后用writeFile写入磁盘.真麻烦呀,还是用spring mvc好.

2
  MultipartForm 的例子,  MultipartForm 中,将上传的文件中的属性配置到
POJO中,例子为:FileUploadForm 类,这个POJO类对应上传的文件类.

  
Java代码 复制代码
  1.  import javax.ws.rs.FormParam;   
  2. import org.jboss.resteasy.annotations.providers.multipart.PartType;   
  3.     
  4. public class FileUploadForm {   
  5.     
  6.     public FileUploadForm() {   
  7.     }   
  8.     
  9.     private byte[] data;   
  10.     
  11.     public byte[] getData() {   
  12.         return data;   
  13.     }   
  14.     
  15.     @FormParam("uploadedFile")   
  16.     @PartType("application/octet-stream")   
  17.     public void setData(byte[] data) {   
  18.         this.data = data;   
  19.     }   
  20.     
  21. }   
  22.     


   处理部分就简单多了,可以这样:
Java代码 复制代码
  1. Path("/file")   
  2. public class UploadFileService {   
  3.     
  4.     @POST  
  5.     @Path("/upload")   
  6.     @Consumes("multipart/form-data")   
  7.     public Response uploadFile(@MultipartForm FileUploadForm form) {   
  8.     
  9.         String fileName = "d:\\anything";   
  10.     
  11.         try {   
  12.             writeFile(form.getData(), fileName);   
  13.         } catch (IOException e) {   
  14.     
  15.             e.printStackTrace();   
  16.         }   
  17.     
  18.         System.out.println("Done");   
  19.     
  20.         return Response.status(200)   
  21.             .entity("uploadFile is called, Uploaded file name : " + fileName).build();   
  22.     
  23.     }  

  即可.

  但总的感觉,REST有点蛋疼,上传个文件,用SPIRNG MVC或者其他方法都可以了,还用
REST这个方法?