ElementUI+Vue实现图片上传及回显

本人所测试文件是用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提交到数据库就行了

图片回显展示:在这里插入图片描述

如果有问题,欢迎与本人交流~

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值