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)
			 }
	
	})
   
}

父组件代码

<el-dialog :visible.sync="showUploadDialog" :modal="false" title="上传图片" width="30%">
		<div style="width:80%;height:80%;justify-content:center;align-items:center;text-align:center;display:flex">
                <div style="margin-bottom:20px;" >
                        <upload-many ref="imgUpload" :data="getChildParam('1','正面照')" @getUploadChildData="getUploadChildData"></upload-many >
                        <el-button type="primary" style="margin-top:10px" @click="uploadRouteImgList" size="mini">提交图片</el-button>

                </div>
        </div>
</el-dialog>

//定义的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("上传图片不能为空")
    }

}

子组件代码

 
<template>
	<div>
	
	<el-upload action="#" 
		accept="image/**" 
        :limit="10" :multiple="true" :auto-upload="false"
		list-type="picture-card" 
        :file-list="data.fileList" 
        :on-change="changeUpload"
		:before-upload="handleBeforeUpload"
		:on-remove="imgRemove"
		:show-file-list="true"
        >
		
		<i class="el-icon-plus"></i>
	</el-upload>
 
	</div>
 </template>
 
 
 <script>
 
 import  {getBase64Url} from '@/api/utils.js'
 
 export default {
	name:"upload",
	props:{
        data:{
            type: Object,
            default:()=>{return {} }
        },
    },
    
	data(){
		return {
			fileList:[],
            imageList:[],
			hideUpload:false,
			imgVisible:false,
			imgUrl:'',
			onChangeImgUrl:'',
            type:'',
            imgUrlArr:[],
		}
	},
    mounted(){
       
       
    },
	 
	methods:{
       
		//上传基本校验
		handleBeforeUpload(file,type){
			var img = file.name.substring(file.name.lastIndexOf('.') + 1)
			const suffix = img === 'jpg'
			const suffix2 = img === 'png'
			const suffix3 = img === 'jpeg'
			const isLt1M = file.size / 1024 / 1024 < 1;
			if (!suffix && !suffix2 && !suffix3) {
				this.$message.error("只能上传图片!");
				return false
			}
			// 可以限制图片的大小
			if (!isLt1M) {
				this.$message.error('上传图片大小不能超过 1MB!');
			}
			return suffix || suffix2 || suffix3
		},
		
		//上传后 删除
		async imgRemove(file ,fileList){
			
			var parentObj = this.data;
            //删除后更新了传给父组件的图片file集合
		    parentObj.routeImgList = fileList;
            this.imgUrlArr =[];
            //删除后更新了传给父组件的图片base64url集合 
            for (let fileTemp of fileList) {
                    const response = await getBase64Url(fileTemp);
                    var res = response.result;
                    res.replace (/^data:image\/\w+;base64/,"");  
                    this.imgUrlArr.push(res);
            }
            parentObj.imgUrlArr = this.imgUrlArr;
            // 传给父组件方法
			this.$emit("getUploadchildData", parentObj);
		},
	
		//上传控件的改变事件 提交到父组件
		async changeUpload(file, fileList){
			
			var parentObj = this.data;
            //删除后更新了传给父组件的图片file集合
		    parentObj.routeImgList = fileList;
			
			//图片转base64
			const response = await getBase64Url(file)
			var res = response.result
            res.replace (/^data:image\/\w+;base64/,"");  
            this.imgUrlArr.push(res);
            parentObj.imgUrlArr = this.imgUrlArr;
			
			 
			this.$emit("getUploadchildData", parentObj);
		}
	
	}
}
 </script>
 
 <style  >
 .img{
    width: 60%;
    height: 80;
    margin: 0 auto;
    display: flex;
    justify-content: center;
    align-items: center;
 }
 </style>

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-30 13:00:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-30 13:00:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-30 13:00:03       82 阅读
  4. Python语言-面向对象

    2024-01-30 13:00:03       91 阅读

热门阅读

  1. 【Vue】2-5、Vue 过滤器

    2024-01-30 13:00:03       46 阅读
  2. 数据双向绑定v-modal

    2024-01-30 13:00:03       54 阅读
  3. el-tree setChecked实现父子不联动

    2024-01-30 13:00:03       53 阅读
  4. Qt基础-QDialog对话框使用

    2024-01-30 13:00:03       58 阅读
  5. IOS 计算富文本的高度方法

    2024-01-30 13:00:03       59 阅读
  6. 再学css

    再学css

    2024-01-30 13:00:03      51 阅读
  7. PySimpleGUI界面读取PDF转换Excel

    2024-01-30 13:00:03       55 阅读
  8. 蓝桥杯-岛屿个数-bfs-dfs算法

    2024-01-30 13:00:03       53 阅读
  9. 华为HCIP Datacom H12-831 卷16

    2024-01-30 13:00:03       65 阅读
  10. 蓝桥杯---错误票据

    2024-01-30 13:00:03       55 阅读
  11. 糊涂工具包使用 记录

    2024-01-30 13:00:03       65 阅读
  12. 51单片机点灯

    2024-01-30 13:00:03       53 阅读
  13. Redis:企业级的深入

    2024-01-30 13:00:03       42 阅读
  14. C语言数据结构——单链表

    2024-01-30 13:00:03       72 阅读