SpringBoot + Vue前后端分离图片上传到本地并前端访问图片

时间:2021-04-18 05:04:32

同理应该可用于其他文件

图片上传

application.yml

配置相关常量

prop:
upload-folder: E:/test/
# 配置SpringMVC文件上传限制,默认1M。注意MB要大写,不然报错。SpringBoot版本不同,配置项不同
spring:
servlet:
multipart:
max-file-size: 50MB
max-request-size: 50MB

Controller

@Value("${prop.upload-folder}")
private String UPLOAD_FOLDER; @PostMapping("/upload")
public Result upload(@RequestParam(name = "file", required = false) MultipartFile file, HttpServletRequest request) {
if (file == null) {
return ResultUtil.error(0, "请选择要上传的图片");
}
if (file.getSize() > 1024 * 1024 * 10) {
return ResultUtil.error(0, "文件大小不能大于10M");
}
//获取文件后缀
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
return ResultUtil.error(0, "请选择jpg,jpeg,gif,png格式的图片");
}
String savePath = UPLOAD_FOLDER;
File savePathFile = new File(savePath);
if (!savePathFile.exists()) {
//若不存在该目录,则创建目录
savePathFile.mkdir();
}
//通过UUID生成唯一文件名
String filename = UUID.randomUUID().toString().replaceAll("-","") + "." + suffix;
try {
//将文件保存指定目录
file.transferTo(new File(savePath + filename));
} catch (Exception e) {
e.printStackTrace();
return ResultUtil.error(0, "保存文件异常");
}
//返回文件名称
return ResultUtil.success(ResultEnum.SUCCESS, filename, request);
}

前端访问图片

前端浏览器在http协议下因为安全原因无法直接访问本地文件

后端拦截器中配置对应url访问本地文件,若有相关拦截器则在拦截器中放行

@Configuration
public class MyInterceptorConfig extends WebMvcConfigurationSupport { @Value("${prop.upload-folder}")
private String UPLOAD_FOLDER; @Autowired
private JwtInterceptor jwtInterceptor; @Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(jwtInterceptor)
.addPathPatterns("/**")
.excludePathPatterns("/login")
.excludePathPatterns("/img/**");
} @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/img/**").addResourceLocations("file:" + UPLOAD_FOLDER);
}
}

前端直接通过/img/图片名称即可拿到