文件上传
form表单有以下要求:
method = "post" # form表单采用post方式提交数据
enctype = "multipart/form-data" # 使用multipart/form-data方式对表单数据进行编码
type = "file" # 使用input的file控件
后台接收:
@Value("${file.basePath}")
private String basePath;
/**
* 上传文件
* @param file 参数名要和前端对应
* @return
*/
@PostMapping("/upload")
public Result upload(MultipartFile file){
String originalFilename = file.getOriginalFilename();// 原始文件名
// 截取文件名后缀
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
// 生成随机文件名(预防重复名字导致文件覆盖)
String fileName = UUID.randomUUID().toString() + suffix;
File dir = new File(basePath);
if(!dir.exists()){
dir.mkdirs();
}
try{
// file 是一个临时文件, 需要转存到指定位置, 否则本次请求完成后临时文件即刻被删除
file.transferTo(new File(basePath + fileName));
}catch(IOException e){
e.printStackTrace();
}
return new Result(1,fileName,"上传成功");
}
文件下载
1.以附件形式下载,弹出保存对话框
2.直接在浏览器中显示
@GetMapping("/download")
public void download(String name, HttpServletResponse response){
try {
// 读取要被下载的内容
File f = new File(basePath + name);
if(!f.exists()){
response.getWriter().print(JSON.toJSONString(new Result(0,"找不到文件")));
return;
}
FileInputStream fileInputStream = new FileInputStream(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 (IOException e) {
e.printStackTrace();
}
}
<!--src只需要写上路径,可以直接展示-->
<body>
<img src="/common/download?name=9ae5af3c-e1bb-4ff7-8850-ba904b502a73.png" alt="">
</body>