application.properties
#上传文件的真实存在路径
file.upload-path=C://file/
#外部访问地址
file.resourceHandler=/upload
WebAppConfig定义映射路径
package com.fxkj.config;
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 WebAppConfig implements WebMvcConfigurer {
@Value("${file.upload-path}")
private String filePathPrefix;
@Value("${file.resourceHandler}")
private String resourceHandler;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(resourceHandler + "/**").addResourceLocations("file:///"+filePathPrefix);
}
}
具体上传代码:
//此处引用application.properties 中定义的参数
@Value("${file.upload-path}")
private String filePathPrefix;
@Value("${file.resourceHandler}")
private String resourceHandler;
/**
* 流下载
* @param file MultipartFile
* @param dto 根据自己的业务逻辑调整
* @param request HttpServletRequest
*/
public Result newUpload(MultipartFile file, UploadDTO dto, HttpServletRequest request) {
try {
log.info("文件上传参数:{},文件名称:{},文件大小:{}", JsonUtils.write(dto), file.getOriginalFilename(), file.getSize());
//防止文件重名自动替换
String[] split = file.getOriginalFilename().trim().split("\\.");
String newFileName = split[0] + "_" + System.currentTimeMillis() + "." + split[1];
String pathPrefix = filePathPrefix +"/";
//根据业务需求拼接文件上传路径:
//此处生成路径:C:\file\2021-02-02\1_1612237804927.jpg
Path path = Paths.get(FileInfoUtils.generatePath(pathPrefix, dateToStr(new Date(), DateUtils.DATE_PATTERN_DEFAULT), newFileName));
//定义线程池
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
//执行线程 上传文件
fixedThreadPool.execute(new UploadFileRunable(file, path.toString()));
//根据自己的业务逻辑处理:
//拼接文件访问地址:basePath+allPath
//allPath: /upload/input_file/2021-02-02/1_1612237804927.jpg
String allPath = resourceHandler + "/" + fileLocation + "/" + DateUtils.dateToStr(new Date(), DATE_PATTERN_DEFAULT) + "/" + newFileName;
//basePath: http://localhost:8085
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
return Result.ok();
} catch (Exception e) {
log.error("文件上传异常:{}", e);
}
return Result.error("文件上传失败!");
}
//文件按上传日期分类
public static final String DATE_PATTERN_DEFAULT = "yyyy-MM-dd";
public static String dateToStr(Date date, String pattern) {
return new DateTime(date).toString(pattern);
}