spring-boot上传文件最佳解决办法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014174854/article/details/79435203

个人技术网站 欢迎关注

很多人使用springboot上传文件的时候最烦的就是上传路径的问题 下面的方法最便捷 最易懂

在配置文件中配置如下

 


 
xcloud:
  #uploadPath: D:/var/uploaded_files/
  uploadPath: C:/Users/renke/apache-tomcat-8.5.24/upload/
media:
  save:
    urlprefix: https://www.xxxxx.com

 

 

 

编写上传路径配置类

@Component
@ConfigurationProperties(prefix="xcloud")
public class UploadConfig {
   //上传路径
   private String uploadPath;

   public String getUploadPath() {
      return uploadPath;
   }

   public void setUploadPath(String uploadPath) {
      this.uploadPath = uploadPath;
   }
}

上传文件方法注入

@Autowired
UploadConfig uploadConfig;
@Value("${media.save.urlprefix}")
private String urlprefix;
/**
 * 本地上传文件接口
 * @param file
 * @param request
 * @return
 * @throws IOException
 */
@CrossOrigin
@PostMapping("/{account}/upload.json")
public Response upload(@RequestParam("file") MultipartFile[] file,@PathVariable("account") String account,
                       HttpServletRequest request) throws IOException {
    log.info("图片上传开始.....");
    if (null != file && file.length > 0) {
        //遍历并保存文件
        for (MultipartFile files : file) {
            if (file != null) {
                //取得当前上传文件的文件名称
                String fileName = account + files.getOriginalFilename();
                //如果名称不为“”,说明该文件存在,否则说明该文件不存在
                //本地上传图片方式
                fileName = FileUtil.renameToUUID(fileName);
                try {
                    FileUtil.uploadFile(files.getBytes(), uploadConfig.getUploadPath(), fileName);
                } catch (Exception e) {
                    return Response.fail("异常");
                }
                    log.info(">>>>>>>>>>>>>本地上传图片路径  {}", "/files/" + fileName);
                    return Response.success().put("fileName", urlprefix + "/files/" + fileName);
            }
        }
    } else {
        return Response.fail("上传文件不能为空");
    }
    return Response.success();
}
然后新建一个WebConfigurer配置类 继承WebMvcConfigurerAdapter
@Slf4j
@Component
class WebConfigurer extends WebMvcConfigurerAdapter {
   @Autowired
   UploadConfig uploadConfig;

   @Override
   public void addResourceHandlers(ResourceHandlerRegistry registry) {
      registry.addResourceHandler("/files/**").addResourceLocations("file:///"+uploadConfig.getUploadPath());
   }
}
这样上传的文件就可以保存在你配置文件中设置的路径中 访问加上前缀就可以指向本地保存路径了 注意一下 有拦截器或者权限拦截的业务时 记得把/filse路径放行才能访问
技术有限 如有疑问 欢迎指导

 
展开阅读全文

没有更多推荐了,返回首页