要想在springboot上实现图片上传功能,要做一下操作
1.创造一个配置类
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
class MyPicConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String path = System.getProperty("user.dir")+"\\src\\main\\resources\\static\\img\\";
// /images/**是对应resource下工程目录
System.out.println(path);
registry.addResourceHandler("/img/**").addResourceLocations("file:"+path);
}
}
其中,System.getProperty(“user.dir”)是当前的工作目录的意思,而addResourceHandler("/img/**").addResourceLocations(“file:”+path)则是为后面的目录创建了一个虚拟访问路径,我们就可以访问前面的路径可以访问图片放在tomcat里面的目录了。
2.配置yml文件
web:
upload-path: E:\workspace\eclipse-jee-workspace\furniturepro\src\main\resources\static\img\
这个是你上传图片到本地里面的目录,如果你只把图片上传到tomcat上面的话,每当你重启项目时,上面的图片就会消失了,所以要把其上传到本地路径里面才行
在yml还要配置这样的代码
resources:
static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${web.upload-path}
这个配置就是当你重启项目时,他就会从本地将你的图片加载到页面上来。
接下来,我觉得最为重要的是实现类,毕竟你写好了service层的实现类后,controller层和页面也不怎么难了,下面是实现类的代码:
@Value("${web.upload-path}")
private String uploadPath;
@Override
public ResponseResult doUpdateAvartar(MultipartFile file, HttpSession session) throws IOException {
if(file==null){
return new ResponseResult(201,"文件为空,请重新输入文件。");
}
if(file.getSize()>1024*1024*10){
return new ResponseResult(202,"文件过大,请重新上传。");
}
String filename = file.getOriginalFilename();
int index = filename.indexOf(".");
String suffix =filename.substring(index);
long time =System.currentTimeMillis();
String newfilename = time+suffix;
String path= session.getServletContext().getRealPath("upload");
System.out.println(path);
File file1 =new File(path);
if(!file1.exists()){
file1.mkdir();
}
String filePath=path+"/"+newfilename;
/*File file2=new File(filePath);*/
File file2=new File(uploadPath,newfilename);
file.transferTo(file2);
System.out.println(filePath);
Integer userId=1;
String userName= (String) session.getAttribute("userName");
String imageName = "http://localhost:8088/furniture/img/"+newfilename;
int row = userMapper.updateAvartar(newfilename,userId,userName);
if(row!=1){
return new ResponseResult(203,"上传图片失败");
}
return new ResponseResult(200,imageName);
}
这就是我全部代码了