`
rensanning
  • 浏览: 3514411 次
  • 性别: Icon_minigender_1
  • 来自: 大连
博客专栏
Efef1dba-f7dd-3931-8a61-8e1c76c3e39f
使用Titanium Mo...
浏览量:37483
Bbab2146-6e1d-3c50-acd6-c8bae29e307d
Cordova 3.x入门...
浏览量:604351
C08766e7-8a33-3f9b-9155-654af05c3484
常用Java开源Libra...
浏览量:678121
77063fb3-0ee7-3bfa-9c72-2a0234ebf83e
搭建 CentOS 6 服...
浏览量:87298
E40e5e76-1f3b-398e-b6a6-dc9cfbb38156
Spring Boot 入...
浏览量:399823
Abe39461-b089-344f-99fa-cdfbddea0e18
基于Spring Secu...
浏览量:69078
66a41a70-fdf0-3dc9-aa31-19b7e8b24672
MQTT入门
浏览量:90494
社区版块
存档分类
最新评论

Spring Boot 入门 - 基础篇(9)- 文件上传下载

 
阅读更多
(1)单文件上传
Form方式
<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方式
$(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)多文件上传
<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)上传文件大小限制
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 # 一次请求的多个文件大小


Nginx的nginx,conf
client_max_body_size 默认是1m,设置为0时,Nginx会跳过验证POST请求数据的大小。
引用
http {
    # ...
    server {
        # ...
        location / {
            client_max_body_size  10m;
        }
        # ...
    }
    # ...
}


Tomcat的server.xml
引用
maxPostSize URL参数的最大长度,-1(小于0)为禁用这个属性,默认为2m
maxParameterCount 参数的最大长度,超出长度的参数将被忽略,0表示没有限制,默认值为10000
maxSwallowSize 最大请求体字节数,-1(小于0)为禁用这个属性,默认为2m


Tomcat 7.0.55之后的版本添加了 maxSwallowSize 参数,默认是2m。maxPostSize对「multipart/form-data」请求不再有效。
<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)文件下载(CSV/Excel/PDF)

CSV文件
@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文件(采用iText生成PDF)
iText具体如何使用参考这里:Java操作PDF之iText超入门
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文件(采用Apache POI生成EXCEL)
POI具体如何使用参考这里:Java读写Excel之POI超入门
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";
}


任意文件
@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";
}


本地文件
@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;
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics