文件上传和下载
/**
* @author zxy
* @createTime 2022-09-14 10:46:00
*/
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
@Value("${reggie.upload.path}")
private String basePath;
/**
* 文件上传
* @param file
* @return
*/
@PutMapping("/upload")
public R<String> upload(MultipartFile file) {
// 获取原文件后缀名
String originalFilename = file.getOriginalFilename();
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
// 使用 UUID 生成新文件名,防止文件名重复造成文件覆盖
String fileName = UUID.randomUUID() + suffix;
// 判断当前目录是否存在,不存在则创建
File dir = new File(basePath);
if (!dir.exists()) dir.mkdirs();
try {
file.transferTo(new File(basePath + fileName));
} catch (IOException e) {
e.printStackTrace();
}
return R.success(fileName);
}
/**
* 文件下载
* @param name
* @param response
*/
@GetMapping("/download")
public void download(String name, HttpServletResponse response) {
FileInputStream fileInputStream = null;
ServletOutputStream outputStream = null;
try {
// 构造输入流,读取文件内容
fileInputStream = new FileInputStream(basePath + name);
// 获取输出流,将文件内容写入响应体
outputStream = response.getOutputStream();
// 设置响应内容类型
response.setContentType("image/jpeg");
// 读写内容
int len = 0;
byte[] bytes = new byte[1024];
while ((len = fileInputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
outputStream.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭资源
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
log.info("文件下载输入流关闭失败~");
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
log.info("文件下载输出流关闭失败~");
}
}
}
}
}