最近项目上有一个需求,用户上传文件后,要返回外部能直接的URL,查了些资料中与搞出来了,该需求的核心点是要将上传文件的路径暴露出来,便于外部通过URL直接访问,即将虚拟路径映射问文件系统的绝对路径
现将过程整理如下:
开发环境:SpringBoot2.0以上、JDK 1.8
spring:
mvc:
static-path-pattern: /**
resources: #设置上传文件目录对外可见,这个参数很重要,不然上传文件对外是访问不到的
static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${serverInfo.uploadpath}
servlet:
multipart: #配置上传文件最大size
max-file-size: 100MB
max-request-size: 100MB
serverInfo: #配置上传文件磁盘存储路径
uploadpath: e:\uploadFile
controller
@PostMapping("upload")
public ResultMsg uploadFile(Integer userId, MultipartFile file) {
long size = (long) file.getSize();
if (size > localConfig.getMaxFileSize()) {
return ResultMsg.getMsg("上传文件过大,请上传小于100MB大小的文件");
}
ResultMsg resultMsg = fileUploadService.uploadFile(senderId,uploadType, file);
return resultMsg;
}
service
@Service
public class FileUploadService {
@Autowired
private LocalConfig localConfig;
public ResultMsg uploadFile(Integer sendId, MultipartFile file){
//获取操作系统文件分隔符
String sepa = java.io.File.separator;
String fileName = file.getOriginalFilename();
String fileNameSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
String fileNamePrefix = fileName.substring(0 , fileName.lastIndexOf("."));
String timeStr = ""+ DateUtils.getDayStr(new Date());
//文件名为:原文件名+上传人Id+上床时间+文件后缀名
String newFileName = fileNamePrefix + "-"+ sendId +"-"+ DateUtils.getDateStr(new Date()) + "." + fileNameSuffix;
//从yml配置文件获取保存文件的根路径
String baseFilePath = localConfig.getUploadFilePath();
//保存文件的路径为:根路径/上传人ID/时间戳/
String path = baseFilePath + sendId+ sepa + timeStr;
//创建文件保存目录
createDirectory(path);
File targetFile = new File(path + sepa + newFileName);
try {
//将上传文件写到服务器上指定的文件
file.transferTo(targetFile);
//构造上传文件的对外访问的URL
String saveUrl =localConfig.getBaseurl()+ sendId+ "/" + timeStr + "/" + newFileName;
FileInfo fileInfo = new FileInfo(newFileName,fileNameSuffix,saveUrl);
return ResultMsg.getMsg(fileInfo);
} catch (IOException e) {
e.printStackTrace();
return ResultMsg.getFailedMsg(e.getMessage());
}
}
public void createDirectory(String directoryPath){
File targetFile = new File(directoryPath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
}
}
FileInfo.java 返回给前端的数据结构,包括文件名、URL、文件后缀名等信息
@Data
public class FileInfo {
public FileInfo(){}
public FileInfo(String fileName,String fileType,String fileUrl){
this.fileName = fileName;
this.fileType= fileType;
this.fileUrl = fileUrl;
}
public String fileName;
public String fileType;
public String fileUrl;
}
LocalConfig.java是配置信息的加载类
@Component
@Data
public class LocalConfig {
public LocalConfig() {}
private Logger logger = LoggerFactory.getLogger(getClass().getName());
@Value("${serverInfo.uploadpath}")
private String uploadFilePath;
@Value("${spring.servlet.multipart.max-file-size}")
private String maxfilesize;
@Value("${serverInfo.baseurl}")
private String baseurl;
public Long getMaxFileSize(){
String str = maxfilesize.substring(0,maxfilesize.length()-2);
Long maxSize = 1024 * 1024 * Long.parseLong(str);
return maxSize;
}
}
评论