@Value("${upload.url}")
private String url;
public static final List list = Arrays.asList("jpg", "png","jpeg","JPEG","JPG","PNG");
public String getImgPaths(MultipartFile[] uploadFile) {
String filePaths= "";
for (MultipartFile file : uploadFile) {
String oldName = file.getOriginalFilename();
String fileType = oldName.substring(oldName.lastIndexOf(".") + 1);
if (!list.contains(fileType)){
throw new BizException("201","图片格式只能为jpg或png");
}
String format = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
File directory=new File(url+format);
if (!directory.exists()){
directory.mkdirs();
}
//1、给上传的图片生成新的文件名
String newName = UUID.randomUUID().toString().replaceAll("-","") + oldName.substring(oldName.lastIndexOf("."));
try {
file.transferTo(new File(directory,newName));
} catch (IOException e) {
e.printStackTrace();
logger.error("图片上传失败", e);
}
if (Objects.equals("",filePaths)){
filePaths= format+"/"+newName;
}else {
filePaths+=";"+format+"/"+newName;
}
}
return filePaths;
}
地址要访问的话需要做映射(或者用nginx)
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Value("${upload.url}")
private String url;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//windows本地文件目录
registry.addResourceHandler("/**").addResourceLocations("file:"+url);
}



