java中使用restful web service来传输文件

【1】上传大文件:

	前端页面:  
		1)同步上传:
			  
				  
					
2)异步上传: 异步上传文件
上传文件:
后端: web.xml CXFServlet org.apache.cxf.transport.servlet.CXFServlet 1 CXFServlet /api/* Spring配置文件: 接口: 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】上传小文件: 前端页面:
后端: 接口: 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 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; }

你可能感兴趣的:(JavaWeb,web基础)