ElementUI+Vue实现图片上传及回显
本人所测试文件是用ElementUI+Vue实现,上传组件用的是ElementUI中的Upload组件,如有不同,请酌情修改!首先,配置文件application.properties#文件上传spring.http.multipart.maxFileSize=100Mbspring.http.multipart.maxRequestSize=100Mbspring.http.mul...
·
本人所测试文件是用ElementUI+Vue实现,上传组件用的是ElementUI中的Upload组件,如有不同,请酌情修改!
首先,配置文件application.properties
#文件上传
spring.http.multipart.maxFileSize=100M
bspring.http.multipart.maxRequestSize=100Mb
spring.http.multipart.location=D:/projectImage/
spring.mvc.static-path-pattern=/**
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${spring.http.multipart.location}
配置文件的作用是指明图片上传之后保存在本地磁盘的位置,如我保存的位置是在D:/projectImage/
页面处理
<el-upload
ref="upload"
action="自己的路径"
list-type="picture-card"
:on-preview="handlePictureCardPreview"
:on-success="handleAvatarSuccess"
:on-remove="handleRemove"
:file-list="fileList"
:auto-upload="false">
<i class="el-icon-plus avatar-uploader-icon"></i>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过1M</div>
</el-upload>
//上传成功的钩子
handleAvatarSuccess(res, file) { //res即为返回的图片路径
if(res!=null){
this.$refs.videoFrom.validate(function(valid) {
if(valid) {
自己的路径绑定变量=res;
//这里面写自己的提交方法
}
})
}
}
后台controller用于接收上传的图片,并返回路径
@Value("${spring.http.multipart.location}")
String rootPath;
@RequestMapping("/upload")
public String uploadPic(HttpServletRequest request) throws Exception{
String requestURI = request.getRequestURI();
Part part = request.getPart("file");
String urlPath = UUID.randomUUID()+part.getContentType().replace("image/", ".");
String coverUrl = "/"+requestURI.split("/")[1]+"/"+urlPath;
IOUtils.copy(part.getInputStream(), new FileOutputStream(rootPath+urlPath));
return coverUrl;
}
简单思路:我这里的图片上传是和其他属性一起放在form表单中的,当点击提交的时候会将图片保存到本地磁盘并将路径保存到数据库,控制层的方法是用来生成一个随机码作为图片的名字以防止重复,然后将路径返回到上传成功的钩子里面,再讲这个路径赋值给你自己的绑定变量,然后用axios提交到数据库就行了
图片回显展示:
如果有问题,欢迎与本人交流~
更多推荐
已为社区贡献1条内容
所有评论(0)