您的位置:首页 > 编程语言 > Java开发

SpringBoot项目中文件上传与下载?

2019-09-10 07:09 1681 查看

一、文件上传

@ApiOperation(value = "文件上传", notes= "文件上传")
@PostMapping("/upload")
public Result upLoadFile(@ApiParam(value = "选择需要上传的文件",required = true) MultipartFile file){
if (file.isEmpty()){
return Result.error(CodeMsg.ERROR);
}
String fileName = file.getOriginalFilename();
long size = file.getSize();
//控制台打印文件信息
System.out.println(fileName+"-->"+size);
//拼接成新的文件名
int index = fileName.indexOf(".");
String suffix = fileName.substring(index);
String name = Date.valueOf(LocalDate.now())+suffix;
//指明文件上传位置
File dest = new File(location, name);
//判断文件父目录是否存在
if(!dest.getParentFile().exists()){
dest.getParentFile().mkdir();
}
try {
//写入文件
file.transferTo(dest);
return Result.success();
} catch (IOException e) {
e.printStackTrace();
return Result.error(CodeMsg.ERROR);
}
}

二、文件下载

@ApiOperation(value = "文件下载", notes = "文件下载")
@GetMapping("/download")
public Result downLoadFile(@ApiParam(value = "填写需要下载的文件") String fileName, HttpServletResponse response){
File file = new File(location, fileName);
if(file.exists()){
response.setContentType("application/force-download");
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
FileInputStream input = null;
try{
input = new FileInputStream(file);
ServletOutputStream out = response.getOutputStream();
int real;
byte[] bytes = new byte[1024];
while((real=input.read(bytes))!=-1){
out.write(bytes, 0, real);
}
return Result.success();
}catch (Exception e){
e.printStackTrace();
return Result.error(CodeMsg.ERROR);
}
}
return Result.error(CodeMsg.ERROR);
}

三、配置文件

spring:
servlet:
multipart:
max-file-size: 100MB #单个文件最大限制
max-request-size: 100MB #总文件上传限制
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Spring YML Spring Boot