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

[b](1)单文件上传[/b]
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);

}


[b](2)多文件上传[/b]
<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);
}

}


[b](3)上传文件大小限制[/b]
src/main/resources/application.properties
[quote]spring.http.multipart.location=${java.io.tmpdir}
spring.http.multipart.max-file-size=1MB # 单文件大小
spring.http.multipart.max-request-size=10MB # 一次请求的多个文件大小[/quote]

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

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

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);
}
}
};
}


[b](4)文件下载(CSV/Excel/PDF)[/b]

[b]CSV文件[/b]
@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);
}


[b]PDF文件(采用iText生成PDF)[/b]
iText具体如何使用参考这里:[url=http://rensanning.iteye.com/blog/1538689]Java操作PDF之iText超入门[/url]
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";
}


[b]Excel文件(采用Apache POI生成EXCEL)[/b]
POI具体如何使用参考这里:[url=http://rensanning.iteye.com/blog/1538591]Java读写Excel之POI超入门[/url]
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";
}


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


[b]本地文件[/b]
@RequestMapping(value = "/downloadTxt2", produces = MediaType.TEXT_PLAIN_VALUE)
public Resource downloadTxt2() {
return new FileSystemResource("abc.txt");
}


[b](5)异常处理[/b]
@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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值