使用jersey上传混合key个file的数据。首先请认真研读官方实例 https://github.com/jersey/jersey/tree/2.19/examples/multipart-webapp
1、配置pom.xml,加入jersey-media-multipart
<dependency> <groupId>org.glassfish.jersey.media</groupId> <artifactId>jersey-media-multipart</artifactId> </dependency>
2、配置serlet入口,web.xml 文件
<servlet> <servlet-name>Jersey Web Application</servlet-name> <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> <init-param> <param-name>jersey.config.server.provider.packages</param-name> <param-value>com.hangyu.dpim</param-value> </init-param> ------ 根据实际情况修改value的值 ------- <init-param> <param-name>javax.ws.rs.Application</param-name> <param-value>com.hangyu.dpim.MyApplication</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
3、编写com.hangyu.dpim.MyApplication类,com.hangyu.dpim.User是会用到该属性的类
package com.hangyu.dpim; import javax.ws.rs.ApplicationPath; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response; import org.glassfish.jersey.media.multipart.MultiPartFeature; import org.glassfish.jersey.server.ResourceConfig; import com.hangyu.dpim.domain.Test; import com.hangyu.dpim.util.RequestResponseUtil; @ApplicationPath("/") public class MyApplication extends ResourceConfig { public MyApplication() { super(com.hangyu.dpim.User.class, MultiPartFeature.class); } }
4、编写接口上传文件
@Path("/upload-avatar") @POST @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.APPLICATION_JSON) public Response uploadAvatar( @FormDataParam("file") String fileString, @FormDataParam("file") InputStream fis, @FormDataParam("file") FormDataContentDisposition fileDisposition, ) throws IOException{ String fullFileName = fileDisposition.getFileName(); String extension = fullFileName.substring(fullFileName.indexOf(".")+1,fullFileName.length()).toLowerCase(); String filePath = FileUtil.writeAvatar(fis, userIDString, extension); return RequestResponseUtil.build200CommonResponse(); }
FileUtil.writeAvatar方法,不仅要保证文件是存在的,还要检查文件夹也是存在的
private static String dirString = "/var/project/dpim"; public static void writeFile(InputStream fis, String path) throws IOException{ System.out.println("path:"+path); File file = new File(path); if (!file.exists()){ file.createNewFile(); } OutputStream fos = new FileOutputStream(file); byte[] buf = new byte[1024]; while ((fis.read(buf)) != -1){ fos.write(buf); } fos.close(); fis.close(); } public static String writeAvatar(InputStream fis, String userID, String extension) throws IOException{ String dirPath = dirString + "/" + userID; File dir = new File(dirPath); if (!dir.exists()){ dir.mkdir(); } String path = dirPath + "/avatar." + extension; writeFile(fis, path); return path; }