图片上传 vue2+element 上传多个图片写法和常见问题1

发布时间 2023-12-20 15:23:04作者: 以后。h

data:

results:接口返回是是[];

 this.formList.result : ''   ;是字符串 , 
resultsList;[];
fileList:[];

注:   因为后台需要接受字符, 上传文件又是 数组,所以需要自己 使用 split(',')  ;join(' ,')    来切换数组和字符串的数据格式

  templete:

table 回显列表:

 results 因为返回得是数组,所以需要遍历出来,    src 需要用 ``  反引号 拼接  ;  getImgList  用来查看,列表图片,可放大缩小

 <el-table-column label="测土配方" min-width="80" props="results">
            <template slot-scope="scope">
              <el-image v-for="(item,index) in scope.row.results"
                :src="url+`${item}`"
                style="width:50px; height: 50px;margin: 0 5px;"
                :key="index"
                :preview-src-list="getImgList(scope.row.results, index)"
               />
        </template>
          </el-table-column>
展示效果:

 

上传组件:

 <el-form-item label="测土配方" prop="results">
            <el-upload
              class="upload-demo"
              action='/api/jsonws/dlapp/add-file-entry'   // 必选参数,上传的地址
              :multiple="true"     //  设置可上传多个
              :auto-upload="true" 
              :before-upload="beforeuplpad"   // 上传文件之前
              :http-request="uploadFileSuccess"  // 文件上传
              :on-error="handleUploadError"    // 上传失败
              accept=".jpg,.jpeg,.png"   // 图片类型
              list-type="picture"   // 文件类型是图片
              :file-list="fileList"   // 图片列表
              :limit="2"    // 最多可上传2张
              :on-exceed="handleExceed" // 上传列表个数限制
              :before-remove="beforeRemove"   //删除之前
              :on-remove="handleRemove"  //  删除之后
            >
              // 这是两种点击上传按钮方式
              <!-- <div class="up-box">
                <i class="el-icon-plus avatar-uploader-icon"></i>
                <span>点击上传图片</span>
              </div> -->
               <el-button size="small" type="primary">点击上传</el-button>
  <!--<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div> -->
            </el-upload>
          </el-form-item>
第一种:

 第二种:

 methods:{

 /*
       * 上传之前的回调
       * */
      beforeuplpad(event) {
        this.imgType = event.type;
        let imgSize = Number(event.size / 1024 / 1024);
        if (imgSize > 100) {
          this.$message({
            message: "文件大小不能超过100M,请重新上传。",
            type: "warning",
          });
          return false;
        }
      },
      uploadCert({ data, file }) {
        uploadFile(file,{fileId:'',itemType:'cert'}).then(res=>{
          this.formList.cert = res.data.savePath
        })
      },
      /*
       * 文件上传
       * */
      uploadFileSuccess({ data, file }) {
        uploadFile(file,{fileId:'',itemType:'result'}).then(res=>{
          let data=res.data.savePath;
          if(data){
            this.resultList.push(data);
          }
        })
      },
      /*
       * 上传失败回调
       * */
      handleUploadError(err) {
        this.$message.error(`上传失败[${err}], 请重试`);
        // Loading.service({
        //  text: "正在上传文件,请稍后...",
        // }).close()
      },
      /***
       * *
       * *
       *     上传列表个数限制
       * ***/
       handleExceed(files, fileList) {
        this.$message.warning('当前最多可选择 2 张图片!');
      },
      // 删除之前
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除该图片?`);
      },
        // 删除之后
      handleRemove(file, fileList) {
        let urlpath = 'http://192.168.122.25:9076'
        let filePath =file.url.slice(urlpath.length)
        if(Array.isArray(this.fileList)&&this.fileList.length){
        let res1 = this.fileList.filter(item=>item.url!=file.url)
        let data=res1.map((item)=>
            item.url.slice(urlpath.length)
        )
        if(Array.isArray(data)&&data.length){
          this.formList.result = data.join(',')
        }
      }
      },
   /** 图片查看 */
      getImgList(workPhoto, index) {
        let arr = []
        if (workPhoto.length == 1) {
          arr.push(workPhoto[0])
        } else if (workPhoto.length == 0)  {
          return arr;
        } else {
          for(let i = 0;i < workPhoto.length;i++){
            arr.push(this.url+workPhoto[i+index])
            if(i+index >= workPhoto.length-1){
              index = 0-(i+1);
            }
          }
        }
        return arr;
      },
 
 //保存 
注意: 新增图片:  上传图片是存到一个新建得数组中,
           编辑:  上传图片是存到一个新建得数组 加上接口返回得数组,
 值得注意得是, 返回得是字符串,  自己上传得是 数组,还是  数组对象,需要自己处理数据,一个不小心就格式混乱了,就报错了,
      to_save() {
        this.$refs.form.validate(async (valid) => {
          if (valid) {
             let newResultList= '';
             let alist=''
            newResultList =this.resultList ? this.resultList.join(',') : ''
            if( newResultList != '' && this.formList.result != ''){
              alist =`${newResultList},${this.formList.result}`
            }else if( newResultList != '' ){
              alist = newResultList
            }else if( this.formList.result != '' ){
              alist = this.formList.result
            }
            this.formList.result = alist
            let row=deepClone(this.formList)
            save_soil(
              row,
            ).then((res) => {
                this.$message({ type: "success", message: res.statusMsg });
                this.to_back();
                this.get_soil_list_by_page();
                this.$refs.form.resetFields();
            });
          }
        });
      },

}

 写法记录就到这里, 下篇开始记录中间遇到得问题以及怎么解决得。拜拜啦!