Springboot 上传文件后,通过虚拟路径访问本地磁盘

网上看到的有用   WebMvcConfigurer  和  WebMvcConfigurerAdapter,试了试,都不行。

最后通过  WebMvcConfigurationSupport   解决的

 

1、application.yml 里增加

file:
  staticAccessPath: /upload/file
#  uploadFolder: e:\\upload\\
  uploadFolder: /home/upload/files/
  #文件上传目录(注意Linux和Windows上的目录结构不同)
  #staticAccessPath 上传文件返回的地址
  #uploadFolder 文件真实存放地址
  #访问文件时   WebAppConfigure 会将返回的地址映射到真实地址

 

2、文件上传

@Value("${file.uploadFolder}")
private String uploadFolder;

@Value("${file.staticAccessPath}")
private String staticAccessPath;
public String uploadfile(@RequestParam("file")MultipartFile file, HttpServletRequest request) {
    SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMdd/HHMMSS");
    String pathDir = uploadFolder + File.separator
            + dateformat.format(new Date()) + (int) Math.random() * 1000
            + File.separator;
    if (File.separator.equals("\\")) {
        pathDir = pathDir.replace("/", "\\");
    }
    String filename = file.getOriginalFilename();

    String extName = "";
    if (null!=filename && filename.length()>0) {
        int t = filename.lastIndexOf(".");
        if (t > 0) {
            extName = filename.substring(t).toLowerCase();
        }
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
    filename = sdf.format(new Date());

    pathDir += filename + extName;
    logger.error("----------文件上传路径------------"+pathDir);
    try {
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(pathDir));
    } catch (IOException e) {
        e.printStackTrace();
    }
    String encodeddata = request.getScheme() + "://域名或者ip"+ request.getContextPath() ;
    return encodeddata+pathDir.replace(uploadFolder,staticAccessPath).replace("\\", "/");
}

 

3、访问时替换路径

public class WebAppConfigure extends WebMvcConfigurationSupport {

    @Value("${file.uploadFolder}")
    private String uploadFolder;

    @Value("${file.staticAccessPath}")
    private String staticAccessPath;



    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) { 

        if(System.getProperty("os.name").toLowerCase().contains("linux")){
            registry.addResourceHandler(staticAccessPath+"/**").addResourceLocations("file:"+uploadFolder);
        }else if(System.getProperty("os.name").toLowerCase().contains("windows")){
            registry.addResourceHandler(staticAccessPath+"/**").addResourceLocations("file:"+uploadFolder);
        }
    }
}

你可能感兴趣的:(Springboot 上传文件后,通过虚拟路径访问本地磁盘)