小编给大家分享一下Springboot项目中如何自定义工具类来实现后台上传图片的操作,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
继承WebMvcConfigurer
重写方法
@SpringBootApplication
//@MapperScan("com.example.demo.Mapper")
public class DemoApplication implements WebMvcConfigurer {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
/*
addResoureHandler:指的是对外暴露的访问路径
addResourceLocations:指的是内部文件放置的目录
*/
registry.addResourceHandler("/imctemp-rainy/**").addResourceLocations("file:D:/image");
}
}
public class UploadUtil {
//源文件名
private String originalFilename;
//源文件后缀名
private String suffix;
//存入数据库里的tomcat虚拟路径
private String dbPath;
//文件大小
private long size;
//实际存储路径
private String realPath;
/**
* 文件上传工具类
* @param attach
* @param request
* @param uploader 文件上传者
* @return
*/
public boolean doUpload(MultipartFile attach, HttpServletRequest request, String uploader){
if(!attach.isEmpty()){
originalFilename = attach.getOriginalFilename();
System.out.println("==>上传的文件名:"+originalFilename);
suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
System.out.println("==>上传的文件后缀名:"+suffix);
size = attach.getSize();
System.out.println("==>上传文件的大小:"+size);
String currentFilename = System.currentTimeMillis()+ UUID.randomUUID().toString() + suffix;
System.out.println("==>存储的上传文件名:"+currentFilename);
realPath = "D:/image/"+uploader ;
System.out.println("==>上传文件保存的真实路径:"+realPath);
File targetFile = new File(realPath, currentFilename);
if(!targetFile.exists()){
targetFile.mkdirs();
}
try{
attach.transferTo(targetFile);
}catch (Exception e){
e.printStackTrace();
return false;
}
realPath = realPath + "/" + currentFilename;
// dbPath = request.getContextPath() + "/" + uploader + "/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" + currentFilename;
dbPath = "/" + uploader + "/" + currentFilename;
return true;
}else{
return false;
}
}
public String getUploadFile(){
return dbPath;
}
}
其中关于路径都需要改成自己存放图片的路径
@RestController
public class UserPhotoController {
@RequestMapping(value = "/upload",method = RequestMethod.POST)
@ResponseBody
public String testUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
UploadUtil uploadUtil = new UploadUtil();
String fileName = "";
if (uploadUtil.doUpload(file, request, "uploadImg")) {
fileName = uploadUtil.getUploadFile();
} else {
fileName = "file";
}
return fileName;
}
}
完成。
以上是“Springboot项目中如何自定义工具类来实现后台上传图片的操作”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。