Analyze the problem of transferring files and other parameters in the upload component of element-ui

Analyze the problem of transferring files and other parameters in the upload component of element-ui

Recently, I used vuethink in my project, which integrated element-ui. I had been using the bootstrap framework before and had only a vague understanding of js. I also used vue.js, but I didn't learn it thoroughly, and then I fell into various pits.

Let me analyze the problems I encountered when using element-ui and their solutions. Please correct me if there are any deficiencies.

First, there is a brief introduction to the upload component on the element-ui official website.

<el-upload
   class="upload-demo"
   action="https://jsonplaceholder.typicode.com/posts/"
   :on-preview="handlePreview"
   :on-remove="handleRemove"
   :file-list="fileList">
   <el-button size="small" type="primary">Click to upload</el-button>
   <div slot="tip" class="el-upload__tip">Only jpg/png files can be uploaded, and the size should not exceed 500kb</div>
</el-upload> 

In fact, upload is to encapsulate input type="file" with several layers of styles

1. action url

The first thing I don't understand is the url in the action. I use PHP in the background. According to my later understanding, this url is actually the upload function used by PHP, just like the action in the form. The difference is that I have been looking for a long time and I can't find whether I can modify the default post delivery method.

While receiving the second file, pass other parameters

Solution 1: URL parameter passing

The most direct way to pass parameters to the URL provided by PHP is to use the post method in the action, but the restful URL I use in the PHP backend cannot pass parameters through the post method. I have tried several methods but failed, and I don't know how to change it to the get method.

The first option can only be abandoned

Solution 2: Do not use action

Give up action. After searching a lot of information, I found that I can use before-upload attribute instead of action. This is a function type attribute. The default parameter is the current file. As long as this file can be passed, the effect can be achieved.

To pass this method, you need to create a new formdata object, and then append key and value to this object, similar to the postman test.

The specific examples given by some people on the Internet are almost as follows

beforeUpload (file) {
      let fd = new FormData()
      fd.append('key', file, fileName)
      axios.post(url, fd.
        //Do some operations})
      return false // false means no automatic upload. I tried it later and found that they were all the same, no automatic upload},

This feels like a good idea, so I wrote it down.

beforeUpload (file,id) {
      let fd = new FormData()
      fd.append('key', file, fileName)
      axios.post(url, fd.
        data:{
         id:id
        }
      })
      return false // false means no automatic upload. I tried it later and found that they were all the same, no automatic upload},

Then I found that no matter what I did, I could only pass the id. In the PHP code, dump(_FLIES) was always NULL. This was very annoying. I searched for a long time but couldn't find a solution. Then I found that the Content-Type I used should be multipart/form-data, but the debugging page in f12 was application/json; charset=utf-8. I thought it might be this problem, so I added headers to the code.

beforeUpload (file,id) {
        let fd = new FormData()
        fd.append('key', file, fileName)
        axios.post(url, fd.
          data:{
           id:id
          },
          headers: {
           'Content-Type': 'multipart/form-data'
          }
        })
        return false // false means no automatic upload. I tried it later and found that they were all the same, no automatic upload},

The error reported this time is axios Missing boundary in multipart/form-data. There is no boundary. It's very annoying.

Later I found that Content-Type is automatically identified and then added with boundaries. Some people also said that Content-Type should be defined as undefined, but it still doesn't work. Content-Type is only automatically identified.

Later I found that formdata and data cannot be passed together. If formdata is to be passed, data cannot be passed, so it should be changed to

beforeUpload (file,id) {
    let fd = new FormData()
    fd.append('file', file)
    fd.append('id',id)
    axios.post(url, fd, {

    })
    return false // false means no automatic upload. I tried it later and found that they were all the same, no automatic upload},

That's it.

Following is my code

<el-upload class="upload-demo"
            drag
            action="123"
            :before-upload="beforeUpload"
            multiple
            ref="newupload"
            :auto-upload="false"
            accept=".mp4,.flv,.mov"
            :on-change="newhandleChange"
            :on-success="newhandlesuccess">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">Drag files here, or <em>click to upload</em> </div>
            <div class="el-upload__tip" slot="tip">Please note that you can only upload video files in .mp4 .flv .mov formats</div>
          </el-upload>
          el-button type="primary" @click="newSubmitForm()" class="yes-btn">
            OK</el-button>
          <el-button @click="resetForm('newform')">
            Reset</el-button>
beforeUpload (file) {
      console.log(file)
      let fd = new FormData()
      fd.append('file', file)
      fd.append('groupId', this.groupId)
      // console.log(fd)
      newVideo(fd).then(res => {
        console.log(res)
      })
      return true
    },
newSubmitForm () {
       this.$refs.newupload.submit()
    },
export function newVideo (data) {
  return axios({
    method: 'post',
    url: 'http://localhost:8086/Platform1-back-end/public/admin/VideoBase/newVideo',
    timeout: 20000,
    data: data
  })
}

I put axios in one file and separated it from the vue file. They are almost the same.

Also, if you add anything to the action, there will be a 404 error, but it does not affect the final effect. If you mind, you can see if there is any way to remove it.

The scheme transmits values ​​multiple times in three steps

I didn't try option 2 because it was successful, but it's pointless and inconvenient.

This is the end of this article about how to pass files and other parameters in the upload component in element-ui. For more relevant content about the upload component in element-ui, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. 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
  • Sample code for uploading multiple files using the element-ui upload component
  • Vue2.0 uses the upload component in element-ui to achieve image preview effect
  • Example of using element-ui's Upload component in a vue project

<<:  Difference between MySQL update set and and

>>:  Window.name solves the problem of cross-domain data transmission

Recommend

How to use JS to parse the excel content in the clipboard

Table of contents Preface 1. Paste Events and Cli...

Implementation of Nginx load balancing cluster

(1) Experimental environment youxi1 192.168.5.101...

Detailed explanation of DOM DIFF algorithm in react application

Table of contents Preface What is VirtualDOM? Rea...

How to load the camera in HTML

Effect diagram: Overall effect: Video loading: Ph...

Detailed deployment of docker+gitlab+gitlab-runner

environment Server: centos7 Client: window Deploy...

Detailed explanation of the group by statement in MySQL database group query

1: Statement order of grouping function 1 SELECT ...

Web Design Tutorial (7): Improving Web Design Efficiency

<br />Previous article: Web Design Tutorial ...

Detailed explanation of MySQL database (based on Ubuntu 14.0.4 LTS 64 bit)

1. Composition and related concepts of MySQL data...

Docker image optimization (from 1.16GB to 22.4MB)

Table of contents The first step of optimization:...

How to use the Linux more command in Linux common commands

more is one of our most commonly used tools. The ...

Graphical introduction to the difference between := and = in MySQL

The difference between := and = = Only when setti...