文件上传与下载

public class CommonController {
@Value("${reggie.path}")
private String basePath; // 正确读取配置文件中的值
// 文件上传
@PostMapping("/upload")
public R<String> upload(MultipartFile file){
// file是个临时文件,需要转存否则,自动删除
// 获得原始文件名
String filename = file.getOriginalFilename();
// .png等格式
String suffix = filename.substring(filename.lastIndexOf("."));
String fileName = UUID.randomUUID().toString()+suffix;
//创建文件夹
File dir = new File(basePath);
// 判断目录是否存在
if (!dir.exists()){
//目录不存在
dir.mkdirs();
}
log.info(file.toString());
// 将临时文件转存
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));
//输出流,通过输出流将文件协会到浏览器,在浏览器展示图片
log.info("文件为{}",fileInputStream);
ServletOutputStream outputStream = response.getOutputStream();
response.setContentType("image/jpeg");
// int用于计算,inteage用于存储
int len;
byte[] bytes=new byte[1024*8];
while ((len=fileInputStream.read(bytes))!=-1){
outputStream.write(bytes,0,len);
outputStream.flush();
}
outputStream.close();
fileInputStream.close();
//关闭资源
} catch (Exception e) {
throw new RuntimeException(e);
}


}

}
posted @   langpo  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
点击右上角即可分享
微信分享提示