以下代码皆在fileService层,fileController层直接调用方法即可就行
文件上传到服务器的目录
//这是配置文件中配置的文件储存目录
@Value("${file.upload.path}")
//D:\java\Project\ManagementSystemSpringbootVue\Back\files\
//若没有最后的斜杠,则在最后一个files的同级目录存东西,即D:\java\Project\ManagementSystemSpringbootVue\Back\
private String fileUploadPath;
@Transactional
@Override
public FilesVO upload(MultipartFile file) {
//先查询数据库是否有该图片(md5是否相等)
// 获取文件的md5
String md5 = null;
try {
md5 = SecureUtil.md5(file.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
// 从数据库查询是否存在相同的记录
Files dbFiles = getFileByMd5(md5);
if (dbFiles != null) { // 文件已存在
FilesVO filesVO = new FilesVO();
BeanUtil.copyProperties(dbFiles, filesVO, true);
return filesVO;
}
else {
//获取这个文件基本信息
//图片.jpg
String originalFilename = file.getOriginalFilename();
//jpg
String contentType = FileUtil.extName(originalFilename);
//图片
String mainName = FileUtil.mainName(originalFilename);
//545454
long size = file.getSize();
// 定义一个文件唯一的标识码
//4asdafasf23rdasda
String uuid = IdUtil.fastSimpleUUID();
//截取7个长度
//图片_4asdafa
String fileUUID = mainName + StrUtil.UNDERLINE + uuid.substring(0, 7);
//图片_4asdafa.jpg
String newFileName = fileUUID + StrUtil.DOT + contentType;
//保存到指定文件夹的唯一名字(路径加文件名)
//D:\java\Project\ManagementSystemSpringbootVue\Back\files\图片_4asdafa.jpg
File uploadFile = new File(fileUploadPath + newFileName);
//D:\java\Project\ManagementSystemSpringbootVue\Back\files
File parentFile = uploadFile.getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs();
}
//用于的下载路径
String url;
// 上传文件到磁盘
try {
//参数的是file型,将收到的文件传输到给定的目标文件夹。
file.transferTo(uploadFile);
// 配置下载路径,下方下载路径的controller层的访问路径
url = "http://localhost:9002/back/file/download/" + newFileName;
} catch (Exception e) {
throw new ServiceException(Constants.CODE_600, "文件上传错误");
}
//文件基本信息
Files files = new Files();
files.setName(fileUUID);
files.setType(contentType);
files.setSize(size / 1024);
files.setMd5(md5);
files.setUrl(url);
//保存到数据库
save(files);
FilesVO filesVO = new FilesVO();
BeanUtil.copyProperties(files, filesVO, true);
return filesVO;
}
}
用于下载访问的service方法
@Transactional
@Override
public void download(String fileUUID, HttpServletResponse response) throws IOException {
// 根据文件的唯一标识码获取文件
File uploadFile = new File(fileUploadPath + fileUUID);
//设置浏览器响应的格式
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, "UTF-8"));
response.setContentType("application/octet-stream");
// 设置输出流的格式
ServletOutputStream os = response.getOutputStream();
// 读取文件的字节流
os.write(FileUtil.readBytes(uploadFile));
os.flush();
os.close();
}
项目目录