Element-UI中el-upload组件的使用

前端代码:
html部分:
<el-upload
class="avatar-uploader"
action="http://localhost:9090/user/uploads/" 上传地址
:show-file-list="false" 是否照片墙也就是单个还是多个
:on-success="handleAvatarSuccess" 成功之后的回调
:before-upload="beforeAvatarUpload" 上传之前做校验
>
<img v-if="imageUrl" :src="imageUrl" class="avatar" /> 上传成功后图片显示的位置
<i v-else class="el-icon-plus avatar-uploader-icon"></i> 上传的加号图标
</el-upload>
<el-button type="primary" size="medium" @click="handleUploads()" style="margin-left: 100px">确认上传</el-button>
js部分:
imageUrl: "",
beforeAvatarUpload(file) { 上传图片之前的校验
const isJPG = file.type === "image/jpeg" || file.type === "image/png"
const isLt2M = file.size / 1024 / 1024 < 2
if (!isJPG) {
this.$message.error("上传头像图片只能是 JPG 或 PNG 格式!")
}
if (!isLt2M) {
this.$message.error("上传头像图片大小不能超过 2MB!")
}
return isJPG && isLt2M
},
handleAvatarSuccess(res, file) { 上传之后让图片显示出来
this.userPicture =res.data
this.imageUrl = URL.createObjectURL(file.raw)
},
每次点击都会向这个接口指定的文件夹上传图片,无论你最后用不用,存到数据库中还需要调用修改方法。
后端代码:
controller层接口:
@PostMapping("/uploads") 这里的形参file必须要和前端传过来的实参保持一致,前端默认就是file
public Result uploadUserPic(MultipartFile file, HttpSession session) throws IOException {
这里的session本来是想做的自动化一点,后来发现还是指定文件夹吧
String url = FileUtils.uploadFile(file, session); 使用了工具类,可复用
return new Result(Code.Request_OK,url,"上传成功!");
}
工具类方法:
public static String uploadFile(MultipartFile photo, HttpSession session) throws IOException {
getOriginalFilename()获取图片的全名,getName()是获取前端file的name
String filename = photo.getOriginalFilename();
UUID防止重名,并且解决中文路径图片不显示的问题,lastIndexOf()可以找到文件后缀jpg前面的点.,再截取获得.jpg
String suffixName = filename.substring(filename.lastIndexOf("."));
重新赋值文件名,前面是一堆字符串加上图片后缀.jpg
filename = UUID.randomUUID().toString() + suffixName;
uploadPath在上面定义了 public static final String uploadPath = ""
String realPath = uploadPath;
创建upload目录对应的File对象,并判断目录是否存在,如果不存在则创建
File file = new File(realPath);
if(!file.exists()) file.mkdir();
图片的最终路径,target下面+通用分隔符+图片名
String finalPath = realPath + File.separator + filename;
使用SpringMVC封装好的transferTo()把文件传输到指定位置,参数是file对象,所以还需要创建最终路径的file
photo.transferTo(new File(finalPath));
不用把最终的路径返回,因为会在配置中设置访问/uploads/**就是访问这里,所以返回upload然后往数据库里存
String url = File.separator + "uploads" + File.separator + filename;
return url;
}
设置映射路径:
@Configuration
public class CorsConfig extends WebMvcConfigurationSupport {
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
当MVC访问 前面的路径时,不会当成路径会看作静态资源,要加上classpath比较好,而且是static而不是resources,因为启动后默认会进入resources文件夹内
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
代表着如果是9090/uploads/...就会自己找到后面的路径,然后读取图片,虽然不正规,但真的很吊!!!!!!,最后地方必须要有两条杠,前面是什么杠这里就怎么写
registry.addResourceHandler("/uploads/**").addResourceLocations("file:/" + FileUtils.uploadPath);
}
}
这就是完整的上传图片(文件)的前后端代码,包括映射路径使之正常显示。