@Value(“${reggie.path}”)
//basePath需要去配置文件定义
private String basePath;
@PostMapping("/upload")
//通过MultipartFile方法上传文件
public R<String> upload(MultipartFile file){
String originalFilename = file.getOriginalFilename();//原始文件名
String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
//使用UUID重新生成文件名,防止文件名称重复造成文件覆盖
String fileName = UUID.randomUUID().toString() + substring;//sdadas.jpg
//创建目录对象
File dir = new File(basePath);
//判断当前目录是否存在
if (!dir.exists()){
//目录不存在需要创建
dir.mkdirs();
}
//file是一个临时文件
try {
file.transferTo(new File(basePath + fileName));
} catch (IOException e) {
throw new RuntimeException(e);
}
return R.success(fileName);
}
//下载文件
@GetMapping("/download")
public void download(String name, HttpServletResponse response){
try{
//输入流,通过输入流读取文件内容
FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
//输出流,通过输出流将文件写回浏览器,在浏览器显示图片
ServletOutputStream 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();
}
//关闭流
outputStream.close();
fileInputStream.close();
}catch (Exception e){
e.printStackTrace();
}
}