springboot~静态文件映射

使用springboot进行文件上传时,你将文件存到磁盘的一个位置,然后通过映射,将这个文件夹映射成应用程序访问的一个路径即可。

资源文件映射

@Configuration
public class WebAppConfigurer implements WebMvcConfigurer {

    @Autowired
    private OssSetting ossSetting;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
                .addResourceLocations("file:///data/upload");
    }
}

文件上传

  public String localUpload(MultipartFile file, String key) {

        String day = DateUtil.format(DateUtil.date(), "yyyyMMdd");
        String path = "/data/upload/" + day;
        File dir = new File(path);
        if(!dir.exists()){
            dir.mkdirs();
        }
        File f = new File(path + "/" + key);
        if(f.exists()){
            throw new PkulawException("文件名已存在");
        }
        try {
            file.transferTo(f);
            return path + "/" + key;
        } catch (IOException e) {
            log.error(e.toString());
            throw new PkulawException("上传文件出错");
        }
    }
posted @ 2022-04-20 15:17  张占岭  阅读(303)  评论(0编辑  收藏  举报