/**
* 上传图片
* @param file
* @return
*/
@Override
public String fileUpload(MultipartFile file) {
//设置文件名,如:ef931b6f-ce9e-49e8-a357-e52c4fc912f7.jpg
String fileName = UUID.randomUUID().toString()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
//System.out.println(uploadDirectory());
try {
byte[] bytes = file.getBytes();
Path path = Paths.get(uploadDirectory() + "/" + fileName);
//写入文件
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
//返回前端
String filename = "../images/" + fileName;
return filename;
}
/**
* 获取static/images/的绝对路径
* @return
* @throws FileNotFoundException
*/
public String uploadDirectory() throws FileNotFoundException {
File path = new File(ResourceUtils.getURL("classpath:").getPath());
if (!path.exists()) {
path = new File("");
}
File upload = new File(path.getAbsolutePath(), "static/images/");
if (!upload.exists()) {
upload.mkdirs();
System.out.println(upload.getAbsolutePath());
}
return upload.getAbsolutePath();
}
SpringBoot上传图片
最新推荐文章于 2024-06-22 16:02:42 发布
该博客主要介绍了如何处理MultipartFile类型的文件上传,通过生成UUID作为文件名,避免重复,并将其保存到指定目录。同时,提供了获取静态资源路径的方法,确保文件能够正确存储和访问。在遇到IOException时,进行了错误处理。
摘要由CSDN通过智能技术生成