1、springboot 2.x
2、application.properties
#单个数据的大小spring.servlet.multipart.maxFileSize=10Mb#总数据的大小spring.servlet.multipart.maxRequestSize=10Mb#文件上传后存储路径:D:\home\capture\5\*.jpg(具体配置如下)#访问Url:http://ip:port/hg-zhwg/upload/5/*.jpg#文件上传目录(window是d/e/f盘, linux是/)(注意Linux和Windows上的目录结构不同)#file.uploadFolder=/file.uploadFolder=d://# 设备截图文件保存路径(文件存在具体的文件夹的路径)zhwg.captrue.image.path=home/capture/#静态资源对外暴露的访问路径(访问图片的路径)file.staticAccessPath=/upload/**
启动类,需要增加multipartConfigElement方法
public class HgZhwgApplication {@Value("${file.uploadFolder}")private String uploadFolder;public static void main(String[] args) {SpringApplication.run(HgZhwgApplication.class, args);}@BeanMultipartConfigElement multipartConfigElement() {MultipartConfigFactory factory = new MultipartConfigFactory();factory.setLocation(uploadFolder);return factory.createMultipartConfig();}}
拦截器中的配置,增加addResourceHandlers方法,指定访问路径。addInterceptors方法需要过滤掉staticAccessPath
@Configurationpublic class WebMvcConfig implements WebMvcConfigurer {@Value("${file.staticAccessPath}")private String staticAccessPath;@Value("${zhwg.captrue.image.path}")private String captureImagePath;@Value("${file.uploadFolder}")private String uploadFolder;@Beanpublic SecutityInterceptor securityInterceptor() {return new SecutityInterceptor();}@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(securityInterceptor()).addPathPatterns("/**").excludePathPatterns("/login/**").excludePathPatterns("/deviceCmd/**").excludePathPatterns("/image/**").excludePathPatterns(staticAccessPath);}@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods("*").maxAge(3600);}@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler(staticAccessPath).addResourceLocations("file:" + uploadFolder + captureImagePath);}}
最后就是上传文件的方法
@RequestMapping("/recive/{devType}/{cmdLogId}")public void reciveCameraCapture(@PathVariable("devType") String devType, @PathVariable("cmdLogId") String cmdLogId,@RequestParam("captureImg") MultipartFile captureImg,@RequestParam(value = "cameraPreviewId", required = false) Long cameraPreviewId,@RequestParam("token") String token, HttpServletRequest request, HttpServletResponse response) {if (captureImg == null) {return;}// 保存图片String filename = captureImg.getOriginalFilename();// 文件后缀名String prefix = filename.substring(filename.lastIndexOf(".") + 1);String destFilename = UUID.randomUUID().toString().replace("-", "") + "." + prefix;File fileUrl = new File(uploadFolder + captureImagePath + devType);if (!fileUrl.exists()) {fileUrl.mkdirs();}File destImage = new File(fileUrl, destFilename);logger.debug("图片保存地址为:" + destImage);try {captureImg.transferTo(destImage);} catch (IOException e) {logger.error("图片保存失败", e);}}
访问:成功