图片上传代码
@value("${tupian.url}")
private String url;
private static final String SEPARATOR = "/";
@Autowired
private StaticImagePath staticImagePath;
@Override
public ResultBean fileUpload(MultipartFile file,Integer type) {
String uuid = UUIDUtils.getUUID();
String fileName = file.getOriginalFilename();
log.info("上传的文件名{}==>"+fileName);
String suffix = fileName.substring(fileName.lastIndexOf("."));
String today = DateUtils.getCurrentDate("yyyy-MM-dd");
String path = staticImagePath.getUploadPath();
//存储文件到磁盘
StringBuilder dictPath = new StringBuilder();
String filetType ="";
if (0 == type){
filetType = "image";
}
if (1 == type){
filetType = "video";
}
dictPath.append(path).append(today).append(SEPARATOR).append(filetType).append(SEPARATOR).append(uuid).append(suffix);
File dictFile = new File(dictPath.toString());
if(!dictFile.getParentFile().exists()) {
dictFile.getParentFile().mkdirs();
}
try {
file.transferTo(dictFile);
} catch (IOException e) {
e.printStackTrace();
return new ResultBean(500,"文件上传失败");
}
JSONObject jsonObject = new JSONObject();
String src = url+today+SEPARATOR+filetType+SEPARATOR+uuid+suffix;
jsonObject.put("src",src);
return new ResultBean(0,"文件上传成功",jsonObject);
}
#网络图片配置
tupian:
uploadPath: d:/img/
url: http://ip:${server.port}/files/
@Data
@Component
@ConfigurationProperties(prefix = "tupian")
public class StaticImagePath {
private String uploadPath;
private String url;
}
@Configuration
public class WebConfigur implements WebMvcConfigurer {
@Autowired
private StaticImagePath staticImagePath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/files/**")
.addResourceLocations("file:///"+staticImagePath.getUploadPath());
registry.addResourceHandler("/**").addResourceLocations(
"classpath:/static/");
registry.addResourceHandler("swagger-ui.html").addResourceLocations(
"classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations(
"classpath:/META-INF/resources/webjars/");
}
}