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

HTML head tag detailed introduction

There are many tags and elements in the HTML head ...

Pagination Examples and Good Practices

<br />Structure and hierarchy reduce complex...

...

Use of MySQL DATE_FORMAT function

Suppose Taobao encourages people to shop during D...

Unity connects to MySQL and reads table data implementation code

The table is as follows: Code when Unity reads an...

Summary of Commonly Used MySQL Commands in Linux Operating System

Here are some common MySQL commands for you: -- S...

How to run a project with docker

1. Enter the directory where your project war is ...

Solution to index failure caused by MySQL implicit type conversion

Table of contents question Reproduction Implicit ...

Example of implementing QR code scanning effects with CSS3

Online Preview https://jsrun.pro/AafKp/ First loo...

Deeply understand how nginx achieves high performance and scalability

The overall architecture of NGINX is characterize...

React entry-level detailed notes

Table of contents 1. Basic understanding of React...

Our thoughts on the UI engineer career

I have been depressed for a long time, why? Some t...

Detailed tutorial on installing harbor private warehouse using docker compose

Overview What is harbor? The English word means: ...

Linux server SSH cracking prevention method (recommended)

1. The Linux server configures /etc/hosts.deny to...