Form方式
Ajax方式
$(function(){ $("#data_upload_button").click(function(event){ event.preventDefault(); if(window.FormData){ var formData = new FormData($(this)[0]); $.ajax({ type : "POST", url : "file/upload", dataType : "text", data : formData, processData : false, contentType: false, }).done(function(data) { alert("OK"); }).fail(function(XMLHttpRequest, textStatus, errorThrown) { alert("NG"); }); }else{ alert("No Support"); } } }); });
@PostMapping("/file/upload") public void upload(@RequestParam("upload_file") MultipartFile multipartFile) { if(multipartFile.isEmpty()){ return; } File file = new File("d://" + multipartFile.getOriginalFilename()); multipartFile.transferTo(file); }
(2)多文件上传
@PostMapping("/file/uploads") public void upload(@RequestParam("upload_files") MultipartFile[] uploadingFiles) { for(MultipartFile uploadedFile : uploadingFiles) { File file = new File("d://" + uploadedFile.getOriginalFilename()); uploadedFile.transferTo(file); } }
(3)上传文件大小限制
src/main/resources/application.properties
引用
spring.http.multipart.location=${java.io.tmpdir}
spring.http.multipart.max-file-size=1MB # 单文件大小
spring.http.multipart.max-request-size=10MB # 一次请求的多个文件大小
spring.http.multipart.max-file-size=1MB # 单文件大小
spring.http.multipart.max-request-size=10MB # 一次请求的多个文件大小
Nginx的nginx,conf
client_max_body_size 默认是1m,设置为0时,Nginx会跳过验证POST请求数据的大小。
引用
http {
# ...
server {
# ...
location / {
client_max_body_size 10m;
}
# ...
}
# ...
}
# ...
server {
# ...
location / {
client_max_body_size 10m;
}
# ...
}
# ...
}
Tomcat的server.xml
引用
maxPostSize URL参数的最大长度,-1(小于0)为禁用这个属性,默认为2m
maxParameterCount 参数的最大长度,超出长度的参数将被忽略,0表示没有限制,默认值为10000
maxSwallowSize 最大请求体字节数,-1(小于0)为禁用这个属性,默认为2m
maxParameterCount 参数的最大长度,超出长度的参数将被忽略,0表示没有限制,默认值为10000
maxSwallowSize 最大请求体字节数,-1(小于0)为禁用这个属性,默认为2m
Tomcat 7.0.55之后的版本添加了 maxSwallowSize 参数,默认是2m。maxPostSize对「multipart/form-data」请求不再有效。
@Bean public TomcatEmbeddedServletContainerFactory containerFactory() { return new TomcatEmbeddedServletContainerFactory() { @Override protected void customizeConnector(Connector connector) { super.customizeConnector(connector); if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol>)) { ((AbstractHttp11Protocol>) connector.getProtocolHandler()).setMaxSwallowSize(-1); } } }; }
(4)文件下载(CSV/Excel/PDF)
CSV文件
@RequestMapping(value = "/downloadCSV", method = RequestMethod.GET) public ResponseEntitydownloadCSV() throws IOException { HttpHeaders h = new HttpHeaders(); h.add("Content-Type", "text/csv; charset=GBK"); h.setContentDispositionFormData("filename", "foobar.csv"); return new ResponseEntity<>("a,b,c,d,e".getBytes("GBK"), h, HttpStatus.OK); }
PDF文件(采用iText生成PDF)
iText具体如何使用参考这里: Java操作PDF之iText超入门
org.springframework.web.servlet.view.document.AbstractPdfView
@Component public class SamplePdfView extends AbstractPdfView { @Override protected void buildPdfDocument(Mapmodel, Document document, PdfWriter writer, HttpServletRequest request, HttpServletResponse response) throws Exception { document.add(new Paragraph((Date) model.get("serverTime")).toString()); } } @RequestMapping(value = "exportPdf", method = RequestMethod.GET) public String exportPdf(Model model) { model.addAttribute("serverTime", new Date()); return "samplePdfView"; }
Excel文件(采用Apache POI生成EXCEL)
POI具体如何使用参考这里: Java读写Excel之POI超入门
org.springframework.web.servlet.view.document.AbstractExcelView
@Component public class SampleExcelView extends AbstractExcelView { @Override protected void buildExcelDocument(Mapmodel, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception { HSSFSheet sheet; HSSFCell cell; sheet = workbook.createSheet("Spring"); sheet.setDefaultColumnWidth(12); cell = getCell(sheet, 0, 0); setText(cell, "Spring Excel test"); cell = getCell(sheet, 2, 0); setText(cell, (Date) model.get("serverTime")).toString()); } } @RequestMapping(value = "exportExcel", method = RequestMethod.GET) public String exportExcel(Model model) { model.addAttribute("serverTime", new Date()); return "sampleExcelView"; }
任意文件
@Component public class TextFileDownloadView extends AbstractFileDownloadView { @Override protected InputStream getInputStream(Mapmodel, HttpServletRequest request) throws IOException { Resource resource = new ClassPathResource("abc.txt"); return resource.getInputStream(); } @Override protected void addResponseHeader(Map model, HttpServletRequest request, HttpServletResponse response) { response.setHeader("Content-Disposition", "attachment; filename=abc.txt"); response.setContentType("text/plain"); } } @RequestMapping(value = "/downloadTxt", method = RequestMethod.GET) public String downloadTxt1() { return "textFileDownloadView"; }
本地文件
@RequestMapping(value = "/downloadTxt2", produces = MediaType.TEXT_PLAIN_VALUE) public Resource downloadTxt2() { return new FileSystemResource("abc.txt"); }
(5)异常处理
@ExceptionHandler(MaxUploadSizeExceededException.class) public ModelAndView handleMaxUploadSizeExceededException(HttpServletRequest req, Exception ex) { ModelAndView model = new ModelAndView("error/fileSizeExceeded"); Throwable t = ((MaxUploadSizeExceededException)ex).getCause(); if (t instanceof FileUploadBase.FileSizeLimitExceededException) { FileUploadBase.FileSizeLimitExceededException s = (FileUploadBase.FileSizeLimitExceededException)t; // ... } if (t instanceof FileUploadBase.SizeLimitExceededException) { FileUploadBase.SizeLimitExceededException s = (FileUploadBase.SizeLimitExceededException)t; // ... } return model; }