java springboot 实现文件上传下载(文件服务器,文件统一处理,图片,word,pdf,视频,等)
1.数据库设计
sql
CREATE TABLE `file_handle` (
`id` varchar(64) NOT NULL,
`file_name` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '文件上传名称',
`file_save_name` varchar(128) DEFAULT NULL COMMENT '重命名文件名称UUID',
`file_type` int DEFAULT NULL COMMENT '文件类型',
`file_path` varchar(255) DEFAULT NULL COMMENT '文件地址',
`file_size` float DEFAULT NULL COMMENT '文件大小',
PRIMARY KEY (`id`)
)
2.文件预览资源配置(Spring MVC框架中用于配置静态资源处理,不安全可以直接访问静态资源不建议使用)
java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class FileHandleConfig implements WebMvcConfigurer {
@Value("${file.dir}")
private String fileDir;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/fileDownload/**")
.addResourceLocations("file:" + fileDir);
}
}
文件访问地址:http://服务器IP:端口/fileDownload/文件名称(文件名必须要唯一)
3.上传接口
java
@Value("${file.dir}")
private String fileDir;
@PostMapping(value = "/upload")
// @TokenChecker
public String upload(MultipartFile file) throws IOException {
String originalFileName = file.getOriginalFilename();
if (StringUtils.isBlank(originalFileName)) {
return Response.Fail(CommonErrorCode.DataNotFound);
}
String extension = originalFileName.substring(originalFileName.lastIndexOf("."));
String newFileName = UUID.randomUUID().toString().replace("-","") + extension;
String upload_file_dir=fileDir;//注意这里需要添加目录信息
String destFileName = fileDir + newFileName;
try {
//第一次运行的时候,这个文件所在的目录往往是不存在的,这里需要创建一下目录(创建到了webapp下uploaded文件夹下)
File upload_file_dir_file = new File(upload_file_dir);
File targetFile = new File(upload_file_dir_file, newFileName);
file.transferTo(targetFile);
FileHandle fileHandle = new FileHandle();
fileHandle.setId(IdUtils.getSnowflakeId(SnowflakeConstant.SYSTEM_MANAGEMENT_ID));
fileHandle.setFileName(originalFileName);
fileHandle.setFilePath(destFileName);
fileHandle.setFileSaveName(newFileName);
fileHandle.setCreateTime(new Date());
fileHandle.setFileType(1);
fileHandle.setDeleted(0);
fileHandle.setFileSize(BigDecimal.valueOf(file.getSize() / (1024.0 * 1024.0)).setScale(2, RoundingMode.HALF_UP));
fileHandleService.save(fileHandle);
if (!upload_file_dir_file.exists()){
upload_file_dir_file.mkdirs();
}
}catch (Exception e){
e.printStackTrace();
}
return Response.OK();
}
4.通过文件ID下载文件(原理也是通过接口下载,这里采取的是文件ID,可以自定义字段下载如文件名称,只要该字段唯一就可以)
java
@Value("${file.dir}")
private String fileDir;
@GetMapping("/download/{fileId}")
public void download(@PathVariable String fileId, HttpServletResponse response) throws IOException {
FileHandle fileHandle = fileHandleService.getById(fileId);
if (fileHandle==null) {
return;
}
File file = new File(fileDir+fileHandle.getFileSaveName());
if (!file.exists()) {
return;
}
String fileName = fileHandle.getFileName();
response.setHeader("Content-Disposition", "attachment;filename=" + URLDecoder.decode(fileName, "UTF-8"));
response.setContentType("application/octet-stream");
// 创建输出流
OutputStream outputStream = response.getOutputStream();
// 读取文件并写入输出流
FileInputStream inputStream = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
}
// 关闭输出流
outputStream.flush();
outputStream.close();
inputStream.close();
}