1.添加依赖:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
2.配置文件上传目录和访问前缀:
// application.yml 文件
# 文件上传下载相关配置
file:
path:
upload: D:/qcby/ #文件上传存储位置,不存在会自动创建
prefix: /filePrefix/ #必须 / 结尾
3.配置映射关系
// WebMvcConfig.java 文件
/**
* @Title: addResourceHandlers
* @Description: 映射本地磁盘为静态目录
* @param: registry
* @throws:
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
FileUtil.filePrefix = filePrefix;
FileUtil.uploadLocalPath = uploadLocalPath;
registry.addResourceHandler(filePrefix +"/**").addResourceLocations("file:"+uploadLocalPath);
}
4.创建一个文件上传工具类
// FileUtil.java 文件
/**
* @Title: uploadFile
* @Description: 单文件上传到本地磁盘
* @param: multipartFile
* @return: java.lang.String
* @throws:
*/
public static String uploadFile(MultipartFile multipartFile){
if(multipartFile == null){
return null;
}
//生成文件名称,以免上传相同文件异常
String fileName = getUploadFileName(multipartFile.getOriginalFilename());
// 获取当前日期
String dateDir = DateUtil.format(null,DateUtil.PATTERN_yyyyMMdd);
// 如果是今天第一次上传,则生成日期文件夹
File destFileDir = new File(uploadLocalPath + File.separator + dateDir);
if(!destFileDir.exists()){
destFileDir.mkdirs();
}
try {
// 获取上传后文件对象
File destFile = new File(destFileDir.getAbsoluteFile()+File.separator+fileName);
// 上传文件到磁盘指定位置
multipartFile.transferTo(destFile);
log.info("文件【"+multipartFile.getOriginalFilename()+"】上传成功");
return filePrefix + dateDir+"/"+fileName;
} catch (IOException e) {
log.error("文件上传异常:"+multipartFile.getOriginalFilename(),e);
return null;
}
}
5.
(1)上传:
@Controller
@RequestMapping("file")
public class FileController {
/**
* 上传文件
* @param file
* @return
*/
@ResponseBody
@RequestMapping("upload")
public ResultJson upload(@RequestParam("file") MultipartFile file){
if(file == null){
return ResultJson.failure(ResultCode.SERVER_ERROR);
}
Map<String,String> r = new HashMap<>();
// 调用上传方法返回可访问的路径
String filePath = FileUtil.uploadFile(file);
// 上传后的路径
r.put("filePath",filePath);
// 文件原名
r.put("oldName",file.getOriginalFilename());
// 文件大小
r.put("size",file.getSize()+"");
return ResultJson.ok(r);
}
}
(2)下载
@Controller
@RequestMapping("file")
public class FileController {
@ResponseBody
@RequestMapping("downloadByFilePath")
public ResponseEntity<byte[]> download(String filePath) throws IOException {
if(StringUtils.isEmpty(filePath)){
throw new RuntimeException("路径不可为空!");
}
/**
* 获取磁盘路径
*/
// 获取到文件相对路径
String path = filePath.substring(filePath.indexOf(FileUtil.filePrefix)+FileUtil.filePrefix.length()-1);
// 磁盘根路径 + 相对路径 获取绝对路径
String localPath = FileUtil.uploadLocalPath+path;
File file = new File(localPath);
if(!file.exists()){
throw new RuntimeException("文件不存在!");
}
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment",
new String(file.getName().getBytes(StandardCharsets.UTF_8), "iso-8859-1"));
headers.add("Access-Control-Expose-Headers", "Content-Disposition");
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
// 获取文件的字节数组 - 需要使用commons-io依赖包
byte[] content = FileUtils.readFileToByteArray(file);
// 返回下载的二进制内容
return new ResponseEntity<>(content, headers, HttpStatus.OK);
}
}