前端:
data(){
return{
form:{
src:""
}
}
}
<el-upload
action="http://localhost:9090/image/upload/"//这个是后端上传图片的接口
list-type="picture-card"
:on-preview="handlePictureCardPreview"
:on-remove="handleRemove"
:on-progress="handleProcess"
:on-success="handleSuccess"//上传成功回调函数
:limit="value"
v-model="form.src">
<i class="el-icon-plus"></i>
</el-upload>
handleSuccess(res,file){
this.form.src=file.response//后端返回的路径,把这个路径保存到数据库就好了
}
后端:
yml文件配置
spring:
servlet:
multipart:
# 单个文件大小
max-file-size: 10MB
# 一次性上传文件的大小
max-request-size: 10MB
server:
port: 9090//服务端口设置
controller请求接口
//上传图片
@PostMapping("/upload")
private String uploadImage(@RequestParam(value = "file") MultipartFile multipartFile) throws IOException {
try{
if(multipartFile.isEmpty()){
return "文件为空,请选择文件";
}
// 上传的图片保存在D://MyWork//毕业设计//学习资源共享系统//upload//image
String uploadPath="D://MyWork//毕业设计//学习资源共享系统//upload//image";
File file=new File(uploadPath);
if(!file.exists()){
// 如果路径不存在则创建完整的目录
file.mkdirs();
}
// 获取文件的原始名称
String originalName=multipartFile.getOriginalFilename();
// 从文件的第一个字符开始到后缀.前结束
String prefixName=originalName.substring(0, originalName.lastIndexOf("."));
// 从.开始获取文件的后缀名
String suffixName=originalName.substring(originalName.lastIndexOf("."));
// 最后拼接的形成文件名
String fileName;
// 获取正确的文件格式,检查文件是否包含后缀
if(originalName.contains(".")){
// 获取当前的时间戳给其一个唯一文件名
fileName=prefixName+"_"+System.currentTimeMillis()+suffixName;
}else{
return "图片格式错误,请重新上传";
}
//将上传的文件保存到指定目录,获取file当前目录+'/'+文件名
String savePath=file.getPath()+File.separator+fileName;
File saveFile=new File(savePath);
FileCopyUtils.copy(multipartFile.getBytes(),saveFile);
//返回给前端的path
String path="http://localhost:9090/image"+File.separator+fileName;
//转统一\格式
if (path.contains("\\")) {
path = path.replace("\\", "/");
}
// 返回path
return path;
}catch (IOException e){
System.out.println(e.getMessage());
}
return "上传错误";
}
映射配置文件
package com.example.springboot.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 配置serve虚拟路径,addResourceHandler为前端访问的url目录,addResourceLocations为files相对应的本地路径
// 如果有一个 upload/image/5_1678789396888.png请求,那程序会到本地的目录文件中找5_1678789396888.png文件
registry.addResourceHandler("/image/**").addResourceLocations("file:D:\\MyWork\\毕业设计\\学习资源共享系统\\upload\\image\\");
}
}
效果如图: