java中使用restful web service來傳輸檔案
阿新 • • 發佈:2019-02-03
【1】上傳大檔案: 前端頁面: 1)同步上傳: <html> <body> <form action="http://localhost:8081/webProject/api/file/uploadFile" method="post" enctype="multipart/form-data"> <input type="file" name="targetFile" /> <input type="text" name="userName" value="jxn" /> <input type="submit" value="提交" /> </form> </body> </html> 2)非同步上傳: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>非同步上傳檔案</title> </head> <body> <form id= "uploadForm" > 上傳檔案: <input type="file" name="sendfile"/> <input type="button" value="上傳" onclick="doUpload()" /> </form> <script src="D:\soft\JQuery\jquery-1.7.2.min.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> function doUpload() { // var formData = new FormData($("#uploadForm")[0]); var formData = new FormData() formData.append("targetFile",$("#sendfile")); formData.append("userName","test-username"); $.ajax({ url: 'http://localhost:8081/webProject/api/file/uploadFile' , type: 'POST', data: formData, async: false, cache: false, contentType: false, processData: false, dataType:'json', success: function (data) { alert(data); } }); } </script> </body> </html> 後端: web.xml <servlet> <servlet-name>CXFServlet</servlet-name> <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class> <load-on-startup>1 </load-on-startup> </servlet> <servlet-mapping> <servlet-name>CXFServlet</servlet-name> <url-pattern>/api/*</url-pattern> </servlet-mapping> Spring配置檔案: <jaxrs:server id="restFileService" address="/file"> <jaxrs:providers> <bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" /> </jaxrs:providers> <jaxrs:serviceBeans> <ref bean="restFileServiceImpl" /> </jaxrs:serviceBeans> </jaxrs:server> <bean id="restFileServiceImpl" class="xxx.api.fileprocess.REST.ApiFileProcessServiceImpl" /> 介面: import org.apache.cxf.jaxrs.ext.multipart.Attachment; import org.apache.cxf.jaxrs.ext.multipart.Multipart; @Path("") public interface ApiFileProcessService { @POST @Path("/uploadFile") @Consumes(MediaType.MULTIPART_FORM_DATA) public String uploadFile(@Multipart(value="targetFile")Attachment targetFile, @Multipart(value="userName")String userName); } 實現: import org.apache.cxf.jaxrs.ext.multipart.Attachment; import javax.activation.DataHandler; public class ApiFileProcessServiceImpl implements ApiFileProcessService { @Override public String uploadFile(Attachment targetFile, String userName) { try { DataHandler dataHandler = targetFile.getDataHandler(); String originalFileName = new String(dataHandler.getName().getBytes("ISO8859-1"),"UTF-8"); InputStream is = dataHandler.getInputStream(); SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); String saveLocation = "D:\\" + df.format(new Date()) + "_" + originalFileName; OutputStream out = new FileOutputStream(new File(saveLocation)); int read = 0; byte[] bytes = new byte[4096]; while ((read = is.read(bytes)) != -1) { out.write(bytes, 0, read); } out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } return "success"; } } 測試結果:可以輕鬆處理(上傳)1G以上的檔案。 【2】上傳小檔案: 前端頁面: <html> <body> <form action="http://localhost:8081/webProject/api/file/uploadCommonFile" method="post" enctype="multipart/form-data"> <input type="file" name="file1" /> <input type="file" name="file2" /> <input type="submit" value="提交" /> </form> </body> </html> 後端: 介面: import javax.ws.rs.core.Context; @Path("") public interface ApiFileProcessService { @POST @Path("/uploadCommonFile") @Consumes(MediaType.MULTIPART_FORM_DATA) public String uploadCommonFile(@Context HttpServletRequest request); } 實現: import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class ApiFileProcessServiceImpl implements ApiFileProcessService { @Override public String uploadCommonFile(HttpServletRequest request) { try { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload fileUpload = new ServletFileUpload(factory); List<FileItem> items = fileUpload.parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { String originalFileName = item.getName(); SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); String saveLocation = "D:\\" + df.format(new Date()) + "_" + originalFileName; File picFile = new File(saveLocation); item.write(picFile); } } } catch (Exception e) { e.printStackTrace(); } return "success"; } } 注意:此方法僅適合上傳小檔案。 【3】下載檔案 case1: 介面: import javax.ws.rs.GET; import javax.ws.rs.QueryParam; @Path("") public interface ApiFileProcessService { @GET @Path("/downloadTemplate") public Response downloadTemplate(@QueryParam("templateName")templateName ); } 實現: import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; public class ApiFileProcessServiceImpl implements ApiFileProcessService { @Override public Response downloadTemplate(String templateName) { File file = null; String fileName = null; try { String applicationPath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath(); file = new File(applicationPath + "/" + templateName); fileName = URLEncoder.encode(templateName, "UTF-8"); // 如果不進行編碼,則下載下來的檔名稱是亂碼 } catch (Exception e) { e.printStackTrace(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } ResponseBuilder response = Response.ok((Object) file); response.header("Content-Disposition", "attachment; filename=" + fileName); return response.build(); } } case2: 介面: import javax.ws.rs.*; import javax.ws.rs.core.Context; @GET @Path("/exportTest") @Produces("application/vnd.ms-excel") public Response exportTest(@FormParam("str") String str, @Context HttpServletResponse response); 實現: import javax.ws.rs.core.Response; import javax.servlet.http.HttpServletResponse; @Override public Response exportTest(String str, HttpServletResponse response) { try { ServletOutputStream outputStream = response.getOutputStream(); SXSSFWorkbook wb = new SXSSFWorkbook(); wb.setCompressTempFiles(true); Sheet sheet = wb.createSheet("sheet0"); Row row = sheet.createRow(0); row.createCell(0).setCellValue("hahaha"); wb.write(outputStream); response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("中文名字.xlsx", "UTF-8")); response.setContentType("application/vnd.ms-excel"); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } return null; }