Springboot 和hutool文件上传下载

1、放开上传限制

servlet:
multipart:
enabled: true #默认支持文件上传
max-file-size: -1 #不做限制
max-request-size: -1 #不做限制
2、设置上传地址
#上传地址
z:
url: http://127.0.0.1:9087/andon/file/
upload: /home/project/file/andon/fileUpload
#获取配置文件地址
@Value("${z.upload}")
private String fileUploadPath;

@Value("${z.url}")
private String fileUploadUrl;

#上传代码
@ApiOperation("8.0 附件_上传")
@PostMapping(value = "/upload")
public Result upload(@RequestParam("file") MultipartFile file,
HttpServletRequest req) throws IOException {
Map<String, Object> map = new HashMap<>();
try {
//文件上传
String hostAddress = InetAddress.getLocalHost().getHostAddress();//获取文件的名称
String filename = file.getOriginalFilename();
//上传的文件夹
String filePath = fileUploadPath;
java.io.File path = new java.io.File(filePath);
if (!path.exists()) {
path.mkdirs();
}
String uuid = IdUtil.simpleUUID();
String fileStr = filename.substring(filename.lastIndexOf("."));
String newFileName = uuid + fileStr;
//上传的文件
String rootFilePath = filePath + newFileName;
log.info("文件写入:" + rootFilePath);
//上传
FileUtil.writeBytes(file.getBytes(), rootFilePath);//使用Hutool工具包将我们接收到文件保存到rootFilePath中
log.info("文件写入成功!");
map.put("filename", filename);
map.put("path", fileUploadUrl + newFileName);
map.put("size", file.getSize());
map.put("loadPath",rootFilePath);
} catch (Exception e) {
log.info("文件上传失败:", e);
}
return Result.success(map);
}

#下载代码

@GetMapping("/{flag}")
@ApiOperation("8.1 附件_下载")
public void getFiles(@PathVariable String flag, HttpServletResponse response, HttpServletRequest req) {
OutputStream os;//新建一个输出流对象
String basePath = fileUploadPath;
List<String> fileNames = FileUtil.listFileNames(basePath);//获取所有的文件名称
String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");//找到跟参数一致的文件
try {
if (StrUtil.isNotEmpty(fileName)) {
java.io.File file = new java.io.File(basePath + fileName);
long length = file.length();
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.setContentType("application/octet-stream");
response.addHeader("totalSize", String.valueOf(length));
response.setContentLengthLong(length);
byte[] bytes = FileUtil.readBytes(file);//通过文件的路径读取文件字节流
os = response.getOutputStream();//通过response的输出流返回文件
os.write(bytes);
os.flush();
os.close();
}
} catch (Exception e) {
log.info("文件下载失败:",e);
}

}
posted @ 2023-02-28 09:10  Aoul  阅读(2646)  评论(0编辑  收藏  举报