目录
文件上传和下载
文件上传
参数
使用MultipartFile 来选择文件
@RequestParam MultipartFile file
获取文件的基本信息
//获取文件名
String originalFilename = file.getOriginalFilename();
//获取文件类型
String type = FileUtil.extName(originalFilename);
//获取文件大小
long size = file.getSize();
将将要保存本地磁盘的路径写在配置文件中
// 从配置文件中取到对应的值
@Value(value = "${files.path}")
private String filePath;
根据md5查询数据库方法
如果数据库中有的话,就不需要添加了
public Files getFileByMd5(String md5){
QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
//查询文件中的md5是否存在
queryWrapper.eq("md5", md5);
List<Files> filesList = filesMapper.selectList(queryWrapper);
return filesList.isEmpty() ? null : filesList.get(0);
}
判断路径是否存在
String UUID = IdUtil.fastSimpleUUID();
// 创建文件名使用uuid拼接StrUtil.DOT为小数点.
String fileUUID = UUID + StrUtil.DOT + type;
//将创建的文件名和路径拼接成绝对路径
File uploadFilePath = new File(filePath + fileUUID );
//判断父级目录是否存在,如果不存在就创建
if (!uploadFilePath.getParentFile().exists()){
uploadFilePath.getParentFile().mkdirs();
}
将文件写入到磁盘中
String url;
//将文件写入到磁盘中
file.transferTo(uploadFilePath);
String md5 = SecureUtil.md5(uploadFilePath);
//根据md5去数据库中查询数据
Files dbFiles = getFileByMd5(md5);
//如果不为空,直接获取url,然后删除刚刚写入磁盘中的
if (dbFiles != null){
url = dbFiles.getUrl();
uploadFilePath.delete();
}else {
url = "http://localhost:9090/file/" + fileUUID;
}
把文件存储到数据库中
Files files = new Files();
files.setType(type);
files.setName(originalFilename);
//文件大小将b转为kb
files.setSize(size/1024);
files.setUrl(url);
files.setMd5(md5);
filesMapper.insert(files);
文件下载
就是这个路径"http://localhost:9090/file/" + fileUUID;就是上面返回的已经拼接好的路径
文件下载,基本都是固定格式
@GetMapping("/{fileUUID}")
public void downloadFile(@PathVariable("fileUUID") String fileUUID , HttpServletResponse response) throws IOException {
File file = new File(filePath + fileUUID);
ServletOutputStream outputStream = response.getOutputStream();
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID,"UTF-8"));
response.setContentType("application/octet-stream");
//读取文件的字节流
outputStream.write(FileUtil.readBytes(file));
outputStream.flush();
outputStream.close();
}
前端处理文件上传下载
上传文件按钮
<el-upload action="http://localhost:9090/file/upload" :show-file-list="false"
:on-success="handleFileUploadSuccesshandle" style="display: inline-block">
<el-button type="primary" style="margin-left: 5px">上传文件<i class="el-icon-bottom"></i></el-button>
</el-upload>
更新头像
以下是核心方法
async getUser(){
return (await this.request.get("/user/username/" + this.users.username)).data
},
save() {
this.request.post("/user/save", this.form).then(res => {
if (res.code === '200') {
this.getUser().then(res => {
//更新浏览器缓存
res.token = JSON.parse(localStorage.getItem("users")).token
localStorage.setItem("users", JSON.stringify(res))
this.users = localStorage.getItem("users") ? JSON.parse(localStorage.getItem("users")) : {}
})
// 刷新页面
location.reload();
this.$message.success("保存成功")
} else {
this.$message.error("保存失败")
}
})
},
handleAvatarSuccess(res) {
this.form.avatarUrl = res
}
结束
有需要前后端完整代码的可以私信我!!!