el-upload子组件上传多张图片(上传为files或base64url)

场景:

在表单页,有图片需要上传,表单的操作行按钮中有上传按钮,点击上传按钮。

弹出el-dialog进行图片的上传,可以上传多张图片。

由于多个表单页都有上传多张图片的操作,因此将上传多图的el-upload定义为公共的子组件。

效果如图:

util.js图片转base64

使用到的工具js,file转url

util.js图片转base64

// 转base64  el-upload上传的file 不能直接用,要用file.raw
// 文件对象转base64
export  function getBase64Url (file) {
	return  new Promise ((resolve,reject) =>{
			  const reader = new FileReader(); //实例化文件读取对象
			  reader.readAsDataURL(file.raw); //将文件读取为 DataURL,也就是base64编码
			 reader.onload = function () {
				resolve(reader)
			 }
			 reader.onerror = function (error) {
				reject(error)
			 }
	
	})
   
}

父组件代码


		
提交图片
//定义的data 省略样式。。。。 showUploadDialog:false,//默认false 点击上传 设置为true uploadRowObj:{},//要上传的对象 // methods 方法 省略样式。。。。 getChildParam(type,title){ var obj = new Object(); obj.type = type; obj.title = title; obj.fileList =[]; obj.routeImgList=[]; return obj; }, //接收子组件上传的base64格式的图片url,赋值给想传给后端的对象 getUploadChildData(obj){ // 这个是files this.uploadRowObj.routeImgList = obj.routeImgList; // 这个是每张图片的base64url 数组 this.uploadRowObj.imgUrlArr = obj.imgUrlArr ; }, //下面写了两种方法,可按需用其中一种 async uploadRouteImgList (){ if(this.uploadRowObj.routeImgList.length>0){ // 第一种 上传files到后端 后端接收为 @RequestParam("id") String id,@RequestParam("files") MultipartFile[] files let formData = new FormData(); this.uploadRowObj.routeImgList.forEach(file=>{ formData.append("files",file); }) formData.append("id", this.uploadRowObj.id); const {code,message,data} = await uploadImg(formData) if(code === '0'){ this.$message.success("上传成功"); this.showUploadDialog = false; } // 第二种 上传的是对象 对象含id和base64Url的数组 (在子组件中 url去除了base64标识的前缀) const {code,message,data} = await uploadImg(this.uploadRowObj) if(code === '0'){ this.$message.success("上传成功"); this.showUploadDialog = false; } }else{ this.$message.error("上传图片不能为空") } }

子组件代码

 

 
 
 
 
 

你可能感兴趣的:(vue.js,javascript,elementui)