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("上傳文件出錯");
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章