使用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("上傳文件出錯");
}
}