Getting Started with Spring Boot - Basics (9) - File Upload and Download

(1) Single file upload
Form method
<form id="data_upload_form" action="file/upload" enctype="multipart/form-data" method="post">
  <input type="file" id="upload_file" name="upload_file" required="" />
  <input id="data_upload_button" type="submit" value="上传" />
</form>


Ajax way
$(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 ("OF");
        });
      }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) Multiple file upload
<form id="data_upload_form" action="file/uploads" enctype="multipart/form-data" method="post">
  <input type="file" id="upload_files" name="upload_files" required="" />
  <input type="file" id="upload_files" name="upload_files" required="" />
  <input type="file" id="upload_files" name="upload_files" required="" />
  <input id="data_upload_button" type="submit" value="上传" />
</form>


@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) Upload file size limit
src/main/resources/application.properties
quote
spring.http.multipart.location=${java.io.tmpdir}
spring.http.multipart.max-file-size=1MB # Single file size
spring.http.multipart.max-request-size=10MB # One request Multiple file sizes


Nginx's nginx, conf
client_max_body_size is 1m by default. When set to 0, Nginx will skip verifying the size of the POST request data.
quote
http {
    # ...
    server {
        # ...
        location / {
            client_max_body_size  10m;
        }
        # ...
    }
    # ...
}


Tomcat-like server.xml
quote
maxPostSize The maximum length of the URL parameter, -1 (less than 0) disables this property, the default is 2m
The maximum length of the maxParameterCount parameter, the parameter exceeding the length will be ignored, 0 means no limit, the default value is 10000
maxSwallowSize The maximum request body bytes Number, -1 (less than 0) to disable this property, the default is 2m


Versions after Tomcat 7.0.55 added the maxSwallowSize parameter, which defaults to 2m. maxPostSize is no longer valid for "multipart/form-data" requests.
<Connector port="8080" protocol="HTTP/1.1"
    connectionTimeout="20000"
    redirectPort="8443"
    useBodyEncodingForURI="true"
    maxSwallowSize="-1" />


@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) File download (CSV/Excel/PDF)

CSV file
@RequestMapping(value = "/downloadCSV", method = RequestMethod.GET)
public ResponseEntity<byte[]> downloadCSV() 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 file (using iText to generate PDF)
For details on how to use iText, please refer to here: iText Super Introduction to PDF Manipulation in Java
org.springframework.web.servlet.view.document.AbstractPdfView

@Component
public class SamplePdfView extends AbstractPdfView {

  @Override
  protected void buildPdfDocument(Map<String, Object> model,
          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 file (using Apache POI to generate EXCEL)
For details on how to use POI, please refer to here: POI Super Introduction to Reading and Writing Excel in Java
org.springframework.web.servlet.view.document.AbstractExcelView

@Component
public class SampleExcelView extends AbstractExcelView {

    @Override
    protected void buildExcelDocument(Map<String, Object> model,
            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";
}


any file
@Component
public class TextFileDownloadView extends AbstractFileDownloadView {

   @Override
   protected InputStream getInputStream(Map<String, Object> model,
           HttpServletRequest request) throws IOException {
       Resource resource = new ClassPathResource("abc.txt");
       return resource.getInputStream();
   }

   @Override
   protected void addResponseHeader(Map<String, Object> 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";
}


local files
@RequestMapping(value = "/downloadTxt2", produces = MediaType.TEXT_PLAIN_VALUE)
public Resource downloadTxt2() {
  return new FileSystemResource("abc.txt");
}


(5) Exception handling
@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;
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326686349&siteId=291194637