Vue uses the Element el-upload component to step on the pit

Vue uses the Element el-upload component to step on the pit

1. Basic Use

I recently studied the el-upload component and stepped on some small pits. I wrote it down for everyone to learn

It is very common to copy the element's components directly to use, but when using the upload component, you will encounter a pitfall.

If you use upload directly, you will definitely encounter this error

And the uploaded pictures may disappear suddenly. At this time, if you don't have an interface, you have no idea why they were removed. So when there is no interface, you can only guess whether the picture disappeared because of a cross-domain error.

Finally, I got the company's address and adjusted the interface. The answer was correct: action="https://jsonplaceholder.typicode.com/posts/". This is the action parameter in element. When using html, it will call ajax, which makes the same-origin policy different and causes an error.

Generally, the company will provide an address link for converting the image into a URL format. You just need to call it and save it. However, you may encounter the need for token permissions. At this time, there is something that is rarely done. Generally, the token is not directly carried through the component, so the token must be carried through the el-upload component.

 <el-upload
            action="https://xxxx address"
            :headers="importHeaders"
          >
   </el-upload>
 
import {getToken} from '@/utils/token'
 
 
data() {
    return {
      importHeaders: {token: getToken()},
    };
  },

2. Image quantity control

 <el-upload
            action="https://security.brofirst.cn/api/common/upload"
            :headers="importHeaders"
            :limit="limit"
             :on-exceed="masterFileMax"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
 
 
 
  // How many pictures can be uploaded at most masterFileMax(files, fileList) {
        console.log(files, fileList);
        this.$message.warning(`Please upload at most ${this.limit} files.`);
    },

3. Image format restrictions/multiple images can be selected

  <el-upload
             accept=".JPG, .PNG, .JPEG,.jpg, .png, .jpeg"
             multiple
          >
            <i class="el-icon-plus"></i>
          </el-upload>

example

   <el-upload
            action="https://xxxx"
            :headers="importHeaders"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleAvatarSuccess"
            :limit="limit"
             :on-exceed="masterFileMax"
             accept=".JPG, .PNG, .JPEG,.jpg, .png, .jpeg"
             multiple
          >
            <i class="el-icon-plus"></i>
          </el-upload>
 
 
 
<script>
import {getToken} from '@/utils/token'
export default {
  name:'feedback',
  data() {
    return {
      importHeaders: {token: getToken()},
       images:[],
      limit:9
    };
  },
  methods: {
  //Delete the picture handleRemove(file, fileList) {
     const idx = this.images.findIndex(it=>it===file.response.data.fullurl)
     this.images.splice(idx,1)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //Data after successful upload handleAvatarSuccess(response, file, fileList){
      console.log(response, file, fileList);
      if(response.code===1){
        this.images.push(response.data.fullurl)
      }
    },
    // How many pictures can be uploaded at most masterFileMax(files, fileList) {
        console.log(files, fileList);
        this.$message.warning(`Please upload at most ${this.limit} files.`);
    }
  }
};
</script> 

Supplement: Use element-ui's Upload component in the vue project

<el-upload
               v-else
               class='ensure ensureButt'
               :action="importFileUrl"
               :data="upLoadData"
               name="importfile"
               :onError="uploadError"
               :onSuccess="uploadSuccess"
               :beforeUpload="beforeAvatarUpload"
               >
               <el-button size="small" type="primary">OK</el-button>

Among them, importFileUrl is the background interface, upLoadData is the additional parameter to be uploaded when uploading files, uploadError is the callback function when the file upload fails, uploadSuccess is the callback function when the file upload is successful, and beforeAvatarUpload is the function called before uploading the file. We can judge the file type here.

data () {
    importFileUrl: 'http:dtc.com/cpy/add',
    upLoadData: {
        cpyId: '123456', 
        occurTime: '2017-08'
    }
},
methods: {
    // Callback after successful uploaduploadSuccess (response, file, fileList) {
      console.log('Upload file', response)
    },
    // Upload error uploadError (response, file, fileList) {
      console.log('Upload failed, please try again!')
    },
    // Determine the file size before uploading beforeAvatarUpload (file) {
      const extension = file.name.split('.')[1] === 'xls'
      const extension2 = file.name.split('.')[1] === 'xlsx'
      const extension3 = file.name.split('.')[1] === 'doc'
      const extension4 = file.name.split('.')[1] === 'docx'
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!extension && !extension2 && !extension3 && !extension4) {
        console.log('The uploaded template can only be in xls, xlsx, doc, docx format!')
      }
      if (!isLt2M) {
        console.log('The uploaded template size cannot exceed 10MB!')
      }
      return extension || extension2 || extension3 || extension4 && isLt2M
    }
}

This is the end of this article about using Element el-upload component in Vue. For more relevant content about Vue Element el-upload component, please search previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Use of vue-cli3.0+element-ui upload component el-upload
  • vue+elementUI (el-upload) image compression, default same ratio compression operation
  • Solve the problem that submit() does not work when the before-upload method of el-upload returns false in vue2.0 element-ui

<<:  How to view nginx configuration file path and resource file path

>>:  MySQL master-slave replication principle and points to note

Recommend

jQuery to achieve the barrage effect case

This article shares the specific code of jQuery t...

Summary of Vue3 combined with TypeScript project development practice

Table of contents Overview 1. Compositon API 1. W...

Understanding v-bind in vue

Table of contents 1. Analysis of key source code ...

Sharing several methods to disable page caching

Today, when developing, I encountered a method wh...

mysql-5.7.28 installation tutorial in Linux

1. Download the Linux version from the official w...

Implementation of new issues of CSS3 selectors

Table of contents Basic Selector Extensions Attri...

Detailed explanation of Angular component projection

Table of contents Overview 1. Simple Example 1. U...

Vue+webrtc (Tencent Cloud) practice of implementing live broadcast function

Table of contents 1. Live broadcast effect 2. Ste...

A brief discussion on HTML doctype and encoding

DOCTYPE Doctype is used to tell the browser which...

VMware workstation 12 install Ubuntu 14.04 (64 bit)

1. Installation Environment Computer model: Lenov...

Introduction to the B-Tree Insertion Process

In the previous article https://www.jb51.net/arti...

Detailed explanation of mysql replication tool based on python

Table of contents 1. Introduction Second practice...

Excel export always fails in docker environment

Excel export always fails in the docker environme...