elment-ui 批量上传图片组件(表单提交时再上传服务器,提交表单)

需求:
1.图片上传限制张数不超过9张、图片类型为jpg/png,图片大小不超过800K;
2.批量选择图片,选择图片之后在页面回显;
3.图片选择完成后不立即上传到服务器,而是在选择之后,提交表单的时候先把图片一张一张的上传到服务器,然后拿到服务器的完整地址,回显到页面;最后提交表单。
选择文件改变事件onchange事件里面限制图片类型、大小、张数,用new FileReader来进行页面回显,在el-upload中绑定ref后,this.$refs.uploadRef.clearFiles()的clearFiles函数:

clearFiles()方法会执行以下操作:

  1. 清空文件列表:它会将组件中的文件列表数据清空,以便用户可以重新选择或上传新的文件。

  2. 重置上传状态:如果你的上传组件有上传状态的标识或进度条,clearFiles()方法可能会将这些状态重置为初始状态。

  3. 可选的其他操作:根据你的需求,clearFiles()方法还可以执行其他的操作,例如清空表单字段、重置验证状态等。
    每次onchange事件执行时,num++
    当执行删除事件时:先移除本地数组imgUrlList中对应下标的item,然后让num--,以确保图片张数的限制正确

代码结构:
<tr>
                  <td class="table-title">图片</td>
                  <td class="table-content">
                    <div class="img-list-container clearAfter">
                      <div
                        class="img-list-item left"
                        v-for="(item, index) in imgUrlList"
                        :key="index"
                      >
                        <div
                          class="remove-img trans"
                          @click="removeImg(item, index)"
                        >
                          x
                        </div>
                        <img :src="item" alt="" />
                      </div>
                    </div>
                    <div>
                      <el-upload
                        class="upload-demo"
                        action=""
                        ref="uploadRef"
                        :show-file-list="false"
                        accept="image/jpeg,image/png"
                        :auto-upload="false"
                        :on-remove="importRemove"
                        :on-change="onChange"
                        :on-exceed="importExceed"
                        :limit="importLimit"
                        :file-list="importFileList"
                        :multiple="multiple"
                      >
                        <el-button size="small" type="primary"
                          >点击上传</el-button
                        >
                        <div slot="tip" class="el-upload__tip">
                          只能上传jpg/png文件,且单张不超过800kb
                        </div>
                      </el-upload>
                    </div>
                  </td>
                </tr>
/*数据定义:*/
importFileList:[],
imgUrlList:[],
importLimit:9,
multiple:true,
num: 0,
courseForm:{ planCourseResources:[],//上传图片}
methods方法:
importRemove(file, fileList) {
          //console.log('importRemove', file, fileList);
        },
        onChange(file, fileList){
          if(this.num>=9) {
            return this.$message.warning('最多只能上传9张图片!');
          }
          const isJPGorPNG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png';
          const isLt800KB = file.raw.size / 1024 <= 800;
          if (!isJPGorPNG) {
            this.$message.error('只能上传jpg/png格式的图片!');
            return false;
          }
          if (!isLt800KB) {
            this.$message.error('单张图片大小不能超过800KB!');
            return false; 
          }
          const reader = new FileReader();
            reader.onload = (e) => {
            const imgUrl = e.target.result;
            // this.imgUrlList.push(imgUrl);
            const arr = [...this.imgUrlList, imgUrl]
            this.imgUrlList = arr
            };
            reader.readAsDataURL(file.raw);
          this.$refs.uploadRef.clearFiles()
          this.num ++
        },
        importExceed(file,fileList){
          console.log("importExceed",file,fileList)
          this.$message.warning('最多只能上传9张图片!');
        },
        //删除图片
        removeImg(_ob,_index){
          console.log('imgUrlList', this.imgUrlList);
          this.imgUrlList.splice(_index, 1);
          this.num--
        },
//新增活动
        addCourse(_status){
let that = this
// 上传所有图片
          that.imgUrlList.map((item) => {
            const formData = new FormData();
            formData.append('image', item);
            const url = 'upload?time=2015101314112&key=02d71a4d46303a8328869dad1ed31f1b';
            //console.log(formData, 'formData');
            that.$querys('imgUpLoad', 'post', url, formData,this.uploadSuccess)
          })
          //图片
          that.courseForm.planCourseResources = [];
          that.imgUrlList.forEach((item,_index)=>{
            that.courseForm.planCourseResources.push({
              resourceUrl:item,
              resourceSeq:_index,
              resourceType:10,
            })
          });
          let _url = 'planCourse/add'
          that.$querys("plan",'post',_url,that.courseForm,that.addCourseBack)
}
uploadSuccess(res){
          //console.log(res,'res');
            const imageUrl = res.data.match(/<h1>.*<\/h1>/)[0].replace('<h1>', '').replace('</h1>', '').replace('MD5: ', '');
            that.imgUrlList.push(basicsUrl['imgUpLoad']+imageUrl)
        },
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
首先,你需要使用Element-UI的upload组件来实现图片上传功能。具体步骤如下: 1. 在Vue组件中引入Element-UI的upload组件,例如: ``` <template> <el-upload class="upload-demo" action="/upload" :on-preview="handlePreview" :on-remove="handleRemove" :before-upload="handleBeforeUpload"> <el-button size="small" type="primary">点击上传</el-button> <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div> </el-upload> </template> ``` 其中,`action`属性指定了图片上传的接口地址,`on-preview`和`on-remove`属性分别指定了预览和删除图片的方法,`before-upload`属性指定了上传图片前的处理方法。 2. 在Vue组件的methods中定义上传图片相关的方法,例如: ``` methods: { handlePreview(file) { console.log('预览图片:', file); }, handleRemove(file, fileList) { console.log('移除图片:', file, fileList); }, handleBeforeUpload(file) { const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'; const isLt500K = file.size / 1024 < 500; if (!isJPG) { this.$message.error('上传图片只能是 JPG/PNG 格式!'); } if (!isLt500K) { this.$message.error('上传图片大小不能超过 500KB!'); } return isJPG && isLt500K; } } ``` 其中,`handlePreview`方法用于预览图片,`handleRemove`方法用于删除图片,`handleBeforeUpload`方法用于对上传的图片进行校验。 3. 在服务器端使用PHP编写图片上传接口,例如: ``` <?php $file = $_FILES['file']; $fileName = $file['name']; $fileTmpName = $file['tmp_name']; $fileSize = $file['size']; $fileError = $file['error']; $fileType = $file['type']; $fileExt = explode('.', $fileName); $fileActualExt = strtolower(end($fileExt)); $allowed = array('jpg', 'jpeg', 'png'); if (in_array($fileActualExt, $allowed)) { if ($fileError === 0) { if ($fileSize < 500000) { $fileNameNew = uniqid('', true) . "." . $fileActualExt; $fileDestination = 'uploads/' . $fileNameNew; move_uploaded_file($fileTmpName, $fileDestination); echo "文件上传成功!"; } else { echo "文件大小超过限制!"; } } else { echo "上传文件发生错误!"; } } else { echo "不支持的文件类型!"; } ?> ``` 其中,`$file = $_FILES['file']`用于获取上传的文件,`$allowed`数组用于指定允许上传的文件类型,`move_uploaded_file`函数用于将上传的文件保存到指定目录下。 最后,你可以在表单提交候将上传的图片路径一起提交服务器端进行保存,具体实现可以根据你的业务需求进行定制。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值