Controller层:
@PostMapping("/uploadfile")
public ResponseResult uploadFile(MultipartFile file) throws IOException {
if (file.isEmpty()) {
return ResponseResult.failResult("文件不能为空");
}
// 这里new的是目录
File dir = new File(FILE_UPLOAD_PATH);
if (!dir.exists() && !dir.isDirectory()) {
// 若不存在该目录,就创建一个
dir.mkdirs();
}
// 根据随机码+时间设置文件名
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String oldName = file.getOriginalFilename();
// 获取后缀
int index = oldName.lastIndexOf('.');
String suffix = oldName.substring(index);
String newName = UUID.randomUUID() + "-" + sdf.format(new Date()) + suffix;
// 将文件保存至服务端的本地
file.transferTo(new File(FILE_UPLOAD_PATH + newName));
// 生成前端路径
String forePortPath = ACCESS_UPLOAD_PATH + newName;
ResponseResult result = ResponseResult.okResult();
result.setData(forePortPath);
return result;
}
配置:
@Configuration
public class MyWebConfiguration extends WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 网页访问资源的路径
registry.addResourceHandler("/upload/**")
.addResourceLocations("file:" + PathConstants.FILE_UPLOAD_PATH);
}
}
常量值:
public interface PathConstants {
String FILE_UPLOAD_PATH = "D:\\mall-uploadfiles\\";
String ACCESS_UPLOAD_PATH = "http://localhost:8080/upload/";
}