spring FileCopyUtils类 上传图片

需要注入ServletContext 

@Autowired
private ServletContext servletContext;
/**
* 上传图片
*/
private String saveFile(MultipartFile file){
if (!file.isEmpty()) {
try {
// getRealPath() 取得 WEB-INF 所在文件夹路径
// 如果参数是 "/temp", temp 存在时返回 temp 的本地路径, 不存在时返回 null/temp (无效路径)
//获取原文件名
String fileName = file.getOriginalFilename();
log.info(fileName);
//文件后缀带点
String suffix = fileName.substring(fileName.lastIndexOf("."));
//新文件名 防止重复
String name= UUID.randomUUID()+suffix;
//文件地址
String path = servletContext.getRealPath("") + "/uplodefiles/"+ name;
//通过流的形式复制文件
FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(path));
//将上传的文件地址返回
String imgurl = StaticFinalVar.Local_URL+"/uplodefiles/"+ name;
System.out.println(imgurl);
return imgurl;
} catch (IOException e) {
e.printStackTrace();
}
}
return "1";
}
原文地址:https://www.cnblogs.com/SeaWxx/p/7986595.html