【1】上传大文件:
1前端页面: 2 1)同步上传: 3 <html> 4 <body> 5 <form action="http://localhost:8081/webProject/api/file/uploadFile" method="post" enctype="multipart/form-data"> 6 <input type="file" name="targetFile" /> 7 <input type="text" name="userName" value="jxn" /> 8 <input type="submit" value="提交" /> 9 </form> 10 </body> 11 </html> 12 13 2)异步上传: 14 <!DOCTYPE html> 15 <html> 16 <head> 17 <meta charset="UTF-8"> 18 <title>异步上传文件</title> 19 </head> 20 <body> 21 <form id= "uploadForm" > 22 上传文件: <input type="file" name="sendfile"/> 23 <input type="button" value="上传" onclick="doUpload()" /> 24 </form> 25 26 <script src="D:\soft\JQuery\jquery-1.7.2.min.js" type="text/javascript" charset="utf-8"></script> 27 <script type="text/javascript"> 28 function doUpload() { 29 // var formData = new FormData($("#uploadForm")[0]); 30 var formData = new FormData() 31 formData.append("targetFile",$("#sendfile")); 32 formData.append("userName","test-username"); 33 $.ajax({ 34 url: 'http://localhost:8081/webProject/api/file/uploadFile' , 35 type: 'POST', 36 data: formData, 37 async: false, 38 cache: false, 39 contentType: false, 40 processData: false, 41 dataType:'json', 42 success: function (data) { 43 alert(data); 44 } 45 }); 46 } 47 </script> 48 </body> 49 </html> 50 51 52后端: 53 54 web.xml 55 <servlet> 56 <servlet-name>CXFServlet</servlet-name> 57 <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class> 58 <load-on-startup>1 </load-on-startup> 59 </servlet> 60 <servlet-mapping> 61 <servlet-name>CXFServlet</servlet-name> 62 <url-pattern>/api/*</url-pattern> 63 </servlet-mapping> 64 65 Spring配置文件: 66 <jaxrs:server id="restFileService" address="/file"> 67 <jaxrs:providers> 68 <bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" /> 69 </jaxrs:providers> 70 <jaxrs:serviceBeans> 71 <ref bean="restFileServiceImpl" /> 72 </jaxrs:serviceBeans> 73 </jaxrs:server> 74 75 <bean id="restFileServiceImpl" class="xxx.api.fileprocess.REST.ApiFileProcessServiceImpl" /> 76 77 78 接口: 79 import org.apache.cxf.jaxrs.ext.multipart.Attachment; 80 import org.apache.cxf.jaxrs.ext.multipart.Multipart; 81 82 @Path("") 83 public interface ApiFileProcessService { 84 [@POST](https://my.oschina.net/u/210428) 85 @Path("/uploadFile") 86 @Consumes(MediaType.MULTIPART_FORM_DATA) 87 public String uploadFile(@Multipart(value="targetFile")Attachment targetFile, @Multipart(value="userName")String userName); 88 } 89 90 实现: 91 import org.apache.cxf.jaxrs.ext.multipart.Attachment; 92 import javax.activation.DataHandler; 93 94 public class ApiFileProcessServiceImpl implements ApiFileProcessService { 95 96 @Override 97 public String uploadFile(Attachment targetFile, String userName) { 98 99 try { 100 DataHandler dataHandler = targetFile.getDataHandler(); 101 String originalFileName = new String(dataHandler.getName().getBytes("ISO8859-1"),"UTF-8"); 102 InputStream is = dataHandler.getInputStream(); 103 104 SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); 105 String saveLocation = "D:\\" + df.format(new Date()) + "_" + originalFileName; 106 107 OutputStream out = new FileOutputStream(new File(saveLocation)); 108 int read = 0; 109 byte[] bytes = new byte[4096]; 110 while ((read = is.read(bytes)) != -1) { 111 out.write(bytes, 0, read); 112 } 113 out.flush(); 114 out.close(); 115 116 } catch (Exception e) { 117 e.printStackTrace(); 118 } 119 120 return "success"; 121 } 122 } 123 124 测试结果:可以轻松处理(上传)1G以上的文件。
【2】上传小文件:
1前端页面: 2 <html> 3 <body> 4 <form action="http://localhost:8081/webProject/api/file/uploadCommonFile" method="post" enctype="multipart/form-data"> 5 <input type="file" name="file1" /> 6 <input type="file" name="file2" /> 7 <input type="submit" value="提交" /> 8 </form> 9 </body> 10 </html> 11 12后端: 13 14 接口: 15 import javax.ws.rs.core.Context; 16 17 @Path("") 18 public interface ApiFileProcessService { 19 @POST 20 @Path("/uploadCommonFile") 21 @Consumes(MediaType.MULTIPART_FORM_DATA) 22 public String uploadCommonFile(@Context HttpServletRequest request); 23 } 24 25 实现: 26 import org.apache.commons.fileupload.FileItem; 27 import org.apache.commons.fileupload.disk.DiskFileItemFactory; 28 import org.apache.commons.fileupload.servlet.ServletFileUpload; 29 30 public class ApiFileProcessServiceImpl implements ApiFileProcessService { 31 @Override 32 public String uploadCommonFile(HttpServletRequest request) { 33 34 try { 35 DiskFileItemFactory factory = new DiskFileItemFactory(); 36 ServletFileUpload fileUpload = new ServletFileUpload(factory); 37 List<FileItem> items = fileUpload.parseRequest(request); 38 39 for (FileItem item : items) { 40 if (!item.isFormField()) { 41 String originalFileName = item.getName(); 42 43 SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); 44 String saveLocation = "D:\\" + df.format(new Date()) + "_" + originalFileName; 45 46 File picFile = new File(saveLocation); 47 item.write(picFile); 48 } 49 } 50 } catch (Exception e) { 51 e.printStackTrace(); 52 } 53 54 return "success"; 55 } 56 } 57 58 59注意:此方法仅适合上传小文件。
【3】下载文件
1case1: 2 接口: 3 import javax.ws.rs.GET; 4 import javax.ws.rs.QueryParam; 5 6 @Path("") 7 public interface ApiFileProcessService { 8 @GET 9 @Path("/downloadTemplate") 10 public Response downloadTemplate(@QueryParam("templateName")templateName ); 11 } 12 13 实现: 14 import javax.ws.rs.core.Response; 15 import javax.ws.rs.core.Response.ResponseBuilder; 16 17 public class ApiFileProcessServiceImpl implements ApiFileProcessService { 18 19 @Override 20 public Response downloadTemplate(String templateName) { 21 22 File file = null; 23 String fileName = null; 24 25 try { 26 String applicationPath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath(); 27 28 file = new File(applicationPath + "/" + templateName); 29 30 fileName = URLEncoder.encode(templateName, "UTF-8"); // 如果不进行编码,则下载下来的文件名称是乱码 31 32 } catch (Exception e) { 33 e.printStackTrace(); 34 return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); 35 } 36 37 ResponseBuilder response = Response.ok((Object) file); 38 response.header("Content-Disposition", "attachment; filename=" + fileName); 39 40 return response.build(); 41 } 42 } 43 44 45 46case2: 47 接口: 48 49 import javax.ws.rs.*; 50 import javax.ws.rs.core.Context; 51 52 @GET 53 @Path("/exportTest") 54 @Produces("application/vnd.ms-excel") 55 public Response exportTest(@FormParam("str") String str, @Context HttpServletResponse response); 56 57 实现: 58 import javax.ws.rs.core.Response; 59 import javax.servlet.http.HttpServletResponse; 60 61 @Override 62 public Response exportTest(String str, HttpServletResponse response) { 63 64 try { 65 ServletOutputStream outputStream = response.getOutputStream(); 66 67 SXSSFWorkbook wb = new SXSSFWorkbook(); 68 wb.setCompressTempFiles(true); 69 70 Sheet sheet = wb.createSheet("sheet0"); 71 Row row = sheet.createRow(0); 72 row.createCell(0).setCellValue("hahaha"); 73 74 wb.write(outputStream); 75 76 response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("中文名字.xlsx", "UTF-8")); 77 response.setContentType("application/vnd.ms-excel"); 78 outputStream.close(); 79 80 } catch (IOException e) { 81 e.printStackTrace(); 82 } 83 84 return null; 85 }