Public multi-type attachment image upload area in Vue page and applicable folding panel (sample code)

Public multi-type attachment image upload area in Vue page and applicable folding panel (sample code)

In front-end projects, attachment uploading is a very common function and is used in almost all app-related projects. Generally, when choosing to use a front-end UI framework, you can find the packaged image upload component in it, but in some cases it may not be suitable for your own project needs. The attachment upload area implemented in this article supports uploading of many types of attachments by type, and can specifically display certain types of attachment uploads according to specific conditions. This article is directly extracted from a specific page, and I will take the time to encapsulate a separate attachment upload component later.

1. Attachment display area code in Vue page

<div class="retuinfo">
          <div class="theadInfo-headline">
            <span></span>
            {{FileDivName}}
          </div>
          <Collapse v-model="defaultCollapse">
            <Panel v-for="(item,pngIndex) in pngFileArray" v-bind:key="pngIndex" :name="item.num" v-show="item.isshow">
              {{item.name}}
              <div class="obsfilesdiv" slot="content">
                <div v-for="(obs,index) in item.files" v-bind:key="index" class="obsfileslist">
                  <input ref="fileImg" type="file" accept="image/*;capture=camera" style="display: none;"
                    @change="setObsFile(item.num,1,obs.FileType,obs.Num,obs.Code)">
                  <label style="color:#6d7180; font-size: 20px;">{{obs.FileType}}<span style="color:red;"
                      v-show="obs.FileType!='Other'">*</span></label>
                  <ul class="obsfilesul">
                    <li v-for="(objitem,objindex) in obs.FileObj" v-bind:key="objindex">
                      <img :src="objitem.imgurl ? objitem.imgurl : fileUrl"
                        @click="showObsFiles(obs.FileFlag,objitem.imgurl)" />
                      <img src="../../../img/other/wrong.png" v-show="objitem.IsCanEdit" class="wrong_class"
                        @click="deleteObsFlie(item.num,index,objindex,objitem.imgid,objitem.imgurl)" />
                    </li>
                    <li style="border: 4px solid #f3f3f3;" @click="PlusClick(obs.FileType,obs.FileFlag,obs.Num)">
                      <img src="../../../img/icon-adds.png" alt="" />
                    </li>
                    <div style="clear:both;"></div>
                  </ul>
                </div>
              </div>
            </Panel>
          </Collapse>
        </div>
        <div class="modal" v-show="viewBigImg">
            <div class="img-view-modal" style="text-align: right;">
                <img :src="viewImgURL" style="width: 100%;" @click="hideShow(0)">
                <Icon type="md-close" style="margin-right: 20px;" size='20' @click="hideShow(0)" />
            </div>
        </div>
      </div>

The Vue project introduces the following UI frameworks: (If you want to use it right away, you need to introduce it in main.js first) IView, MintUI, Vant This code can be used normally as long as IView is introduced

2. Data Binding Design

I won't go into detail, but arrays and property control are easy to understand.

pngFileArray: [{
            num: '0',
            name: 'Complete vehicle',
            isshow: localStorage.getItem("RoleName").indexOf('Nameplate Quality Inspector') != -1 ? true : false,
            files: [ //FileFlag://1:Picture; 2:Video 3.Others {
                FileType: 'Vehicle nameplate image',
                Code: '201',
                Num: 0,
                FileFlag: 1,
                FileObj: [],
                IsNoFile: true
              },
              {
                FileType: 'VIN image of vehicle frame',
                Code: '207',
                Num: 1,
                FileFlag: 1,
                FileObj: [],
                IsNoFile: true
              },
              {
                FileType: 'Terminal Image',
                Code: '301',
                Num: 2,
                FileFlag: 1,
                FileObj: [],
                IsNoFile: true
              }
            ]
          },
          {
            num: '1',
            name: 'Mileage',
            isshow: localStorage.getItem("RoleName").indexOf('Account Manager') != -1 ? true : false,
            files: [{
                FileType: 'Odometer Photo',
                Code: '701',
                Num: 3,
                FileFlag: 1,
                FileObj: [],
                IsNoFile: true
              }
            ]
          }
        ],

3. Binding Method

1. Image loading method:

//Get the image list getImageList() {
        this.$indicator.open({
          text: 'Image loading...',
          spinnerType: 'snake'
        });
        let _this = this;
        let downRequest = {
            'crm_vin': this.parms.crm_vin,
            'crm_vehiclenumber': this.parms.crm_vehiclenumber
          };
        let imgListParams = {
          "ImageDownRequest": JSON.stringify(downRequest),
          "username": localStorage.getItem("usernameone"),
          "password": localStorage.getItem("password")
        };
        console.log("Get the image list parameters:", imgListParams);
        _this.$ajax.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded;'; //Configure request header this.$ajax.post(this.imageListUrl, this.$qs.stringify(imgListParams)).then(resdata => {
          _this.$indicator.close();
          console.log("Get the image list data:", resdata);
          let data = resdata.data;
          console.log("Converted image list data:", data);
          if (resdata.status != 200) {
            _this.$toast({
              message: 'Failed to get the image list! ',
              duration: 3000
            });
            return;
          }
          // Clear the original image list first_this.pngFileArray.forEach((rr,index,array) =>{
            for(var file=0;file<rr.files.length;file++){
              _this.pngFileArray[index].files[file].FileObj = [];
              _this.pngFileArray[index].files[file].IsNoFile = true;
            }
          });
          //Write the image list into each image classification area of ​​the page for(var i=0;i<data.length;i++){
            _this.pngFileArray.forEach((rr,index,array) => {
              for(var file=0;file<rr.files.length;file++){
                if(data[i].crm_imagetypeno==rr.files[file].Code){
                  let putparm = {
                    "IsCanEdit":false,
                    "imgid": data[i].crm_careimageId,
                    "imgurl": data[i].ImageUrl
                  };
                  _this.pngFileArray[index].files[file].FileObj.push(putparm);
                  _this.pngFileArray[index].files[file].IsNoFile = false;
                }
              }
            });

          }
        }).catch(function(error) {
          _this.$indicator.close();
          _this.$toast({
            message: error,
            duration: 3000
          });
        });
      },

2. Picture display method

showObsFiles(type, url) { //Show pictures or videos console.log("Show attachments: " + type);
        if (type == 1) { //Picture this.viewBigImg = true;
          this.viewImgURL = url;
        } else { //File this.$messagebox.alert("File viewing is not supported, please operate on PC!", "Prompt");
          return;
        }
      },

3. Related methods for uploading pictures

(The original design was to support uploading of pictures, videos and other types of files, which has been implemented in the project and will not be expanded in this article)

PlusClick(type, flag, num) {
        console.log("Current attachment type: " + type);
        console.log("Current attachment number: " + num);
        this.currentFileType = type;
        if (flag == 1) { // Image upload this.$refs.fileImg[num].dispatchEvent(new MouseEvent('click'));
        } else if (flag == 2) { // Video upload this.$refs.fileVideo[num].dispatchEvent(new MouseEvent('click'));
        } else { // Other types of files this.$refs.filElem[num].dispatchEvent(new MouseEvent('click'));
        }
      },
setObsFile(classify, type, obsFileType, num, code) { //Save the image to crm var _this = this;
        var inputFile; //File stream console.log("Image classification: " + classify + " " + obsFileType + " " + num) + "Image encoding: " + code;
        if (type == 1) {
          inputFile = this.$refs.fileImg[num].files[0];
          this.$refs.fileImg[num].value = '';
        }
        var fileName = inputFile.name;
        if (!inputFile) {
          return;
        }
        if (inputFile.type == 'image/jpg' || inputFile.type == 'image/jpeg' || inputFile.type == 'image/png' ||
          inputFile.type ==
          'image/gif') {} else {
          this.$messagebox.alert("Please upload a picture", "Prompt");
          return;
        }
        _this.$indicator.open({
          text: 'File uploading, please wait...',
          spinnerType: 'snake'
        });
        //Image compression and conversion into base64 file stream var reader = new FileReader();
        reader.readAsDataURL(inputFile);
        reader.onloadend = function(e) {
          let result = this.result;
          console.log('********Uncompressed image size********:' + result.length / 1024)
          _this.pulic.dealImage(result, {}, function(base64) {
            console.log('********Compressed image size********:' + base64.length / 1024)
            _this.putObsFile(classify, fileName, base64, obsFileType, code);
          });
          //reader.result.substring(this.result.indexOf(',')+1);
          // 'data:image/png;base64,'+reader.result
        }
      },
      putObsFile(classify, fileName, base64, obsFileType, code) { //Extract the public uploaded image file method var _this = this;
        let usernameone = this.$Base64.encode("administrator");
        let password = this.$Base64.encode("pass@word1");
        let parmsImages = {
          crm_newenergyid: localStorage.getItem("crm_newenergyid"),
          vin: _this.parms.crm_vin,
          crm_vehiclenumber: _this.parms.crm_vehiclenumber,
          CareType: code,
          CreateBy: localStorage.getItem("SystemUserId"),
          ImageStr: base64.split(",")[1],
          username: usernameone,
          password: password
        }
        let parms = {
          ImageMessage: JSON.stringify(parmsImages)
        }
        console.log(JSON.stringify(parmsImages));
        console.log(JSON.stringify(parms));
        _this.$ajax.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded;'; //Configure request header _this.$ajax.post(_this.imageSaveUrl, _this.$qs.stringify(parms))
          .then(resdata => {
            _this.$indicator.close();
            console.log("Interface response data:", resdata);
            let data = resdata.data;
            console.log("Converted response data:", data);
            if (resdata.status != 200) {
              _this.$toast({
                message: 'Save failed! Interface call exception',
                duration: 3000
              });
              return;
            }
            //Write the uploaded image url back to the image classification url on the page console.log("All image types under the current classification: " + JSON.stringify(_this.pngFileArray[parseInt(classify)].files));
            for (var i = 0; i < _this.pngFileArray[parseInt(classify)].files.length; i++) { //Traverse the image type array under the current category and assign the data returned by the background if (obsFileType == _this.pngFileArray[parseInt(classify)].files[i].FileType) {
                //Set the image file path etc. putparm
                let putparm = {
                  "IsCanEdit":true,
                  "imgid": data.crm_careimageId,
                  "imgurl": data.ImageUrl
                };
                _this.pngFileArray[parseInt(classify)].files[i].FileObj.push(putparm);
                _this.pngFileArray[parseInt(classify)].files[i].IsNoFile = false;
              }
            }
            _this.$messagebox.alert("Attachment uploaded successfully", "Prompt");
          }).catch(err => {
            console.log(JSON.stringify(err));
            _this.$toast({
              message: 'Upload failed',
              duration: 1500
            });
            _this.$indicator.close();
          });
      },

4. How to delete pictures

(In this article, only unsubmitted images can be deleted. Submitted images, i.e. images obtained when the page is initially loaded, cannot be deleted.)

deleteObsFlie(classify,num,index,id,url) { //Delete attachment var _this = this;
        this.$messagebox.confirm('Are you sure you want to delete this image?', "Confirm").then(action => {
          var del_param = {
            "id": id,
            "url": url
          };
          _this.$indicator.open({
            text: 'Deleting pictures, please wait...',
            spinnerType: 'snake'
          });
          _this.$ajax.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded;'; //Configure request header _this.PromiseCall(_this.DelImgFilesURL, _this.$qs.stringify(del_param))
            .then(data => {
              _this.$indicator.close();
              console.log(JSON.stringify(data));
              if (data.status != 200) {
               _this.$messagebox.alert("Failed to delete the image", "prompt");
               return;
              }
              _this.pngFileArray[parseInt(classify)].files[num].FileObj.splice(index, 1);
              _this.$toast({
                message: 'Deleted the image successfully',
                duration: 1500
              });
            }).catch(err => {
              _this.doCatch(err);
              _this.$toast({
                message: 'Failed to delete the image'+err,
                duration: 1500
              });
              _this.$indicator.close();
            });
        });
      },

4. CSS style

.retuinfo {
    width: 96%;
    height: auto;
    margin-top: 20px;
    margin-left: 2%;
    background-color: #F5F7FA;
    border-radius: 15px;
  }
.theadInfo-headline {
    width: 100%;
    height: 80px;
    background: #F3F3F3;
    display: flex;
    padding-left: 30px;
    align-items: center;
    font-size: 28px;
    color: #666666;
    border-radius: 15px;
  }
  .theadInfo-headline span {
    width: 6px;
    height: 32px;
    background: #5576AB;
    border-radius: 3px;
    margin-right: 10px;
  }
.ivu-collapse-header {
    height: 40px;
    align-items: center;
    display: flex;
  }
.obsfilesdiv {
    width: 100%;
    height: auto;
    margin-top: .5rem;
    margin-bottom: 50px;
}
.obsfileslist {
    width: 100%;
    height: auto;
    padding: 0.5rem 0.5rem;
    background: #fff;
}
.obsfilesul {
    width: 100%;
    height: auto;
    padding-bottom: 8px;
}
.obsfilesul li {
    width: 120px;
    height: 120px;
    float: left;
    margin-top: .3rem;
    overflow: hidden;
    margin-right: .3rem;
    border: none;
}
.obsfilesul li img {
    width: 100%;
    height: 100%;
}
.imglist {
    width: 100%;
    margin-top: .5rem;
    margin-bottom: 6rem;
}
.modal {
    background-color: #A9A9A9;
    position: fixed;
    z-index: 99;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    padding-top: 4rem;
    /*opacity: 0.5;*/
    align-items: center;
    /*Define the vertical center of the body element*/
    justify-content: center;
    /*Define the horizontal center of the elements in the body*/
}
.modal img {
    animation-name: zoom;
    animation-duration: 0.6s;
    display: block;
    padding: 10px;
    margin: auto;
    max-width: 100%;
    max-height: 100%;
    box-shadow: 0 2px 6px rgb(0, 0, 0, 0), 0 10px 20px rgb(0, 0, 0, 0);
    border-radius: 12px;
    border: 1px solid white;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
}
.showname {
    width: 100px;
    height: 60px;
    position: relative;
    top: -4.5rem;
    white-space: normal;
    word-break: break-all;
    word-wrap: break-word;
}
.wrong_class {
    width: 30% !important;
    height: 30% !important;
    position: relative;
    top: -3.8rem;
    left: 2.6rem;
}
.wrongs_class {
    width: 4% !important;
    height: 4% !important;
    position: relative;
    /*top: -5.2em;*/
    left: 0.5rem;
}

Finally, the actual effect diagram is attached:

This concludes this article about the public multi-type attachment image upload area in the Vue page and the applicable folding panel. For more relevant Vue multi-type attachment image upload content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Four solutions to the problem of data loss when refreshing vuex pages
  • Vue multi-page project development practical guide
  • How does Vue implement cross-page transmission and reception of arrays and assignment
  • Vue implements pop-up window to reference another page window
  • vue jumps to the page and opens a new window, carrying and receiving parameters
  • Distributed medical registration system - building the backend management system page

<<:  HTML page jump passing parameter problem

>>:  Bootstrap3.0 study notes table related

Recommend

Seven different color schemes for website design experience

The color matching in website construction is ver...

Analysis of the HTML writing style and reasons of experienced people

1. Navigation: Unordered List vs. Other Label Ele...

JS function call, apply and bind super detailed method

Table of contents JS function call, apply and bin...

Adobe Brackets simple use graphic tutorial

Adobe Brackets is an open source, simple and powe...

Detailed explanation of the use of grid properties in CSS

Grid layout Attributes added to the parent elemen...

Mini Program Recording Function Implementation

Preface In the process of developing a mini progr...

What is a MySQL tablespace?

The topic I want to share with you today is: &quo...

MySQL index coverage example analysis

This article describes MySQL index coverage with ...

DOCTYPE element detailed explanation complete version

1. Overview This article systematically explains ...

Basic usage examples of listeners in Vue

Table of contents Preface 1. Basic usage of liste...

Detailed installation and use of virtuoso database under Linux system

I've been researching some things about linke...

How to modify the default encoding of mysql in Linux

During the development process, if garbled charac...

Implementation of Docker to build private warehouse (registry and Harbor)

As more and more Docker images are used, there ne...