Summary of the Experience of element Upload Component el-upload

Posted by fleabel on Mon, 29 Jul 2019 06:07:24 +0200

Preface

Recent background management projects, the use of the _____________ vue-element-admin Uploading pictures is a very common function, but also encountered many problems, just take this opportunity to do some summary.

The list of questions that will be raised in the preliminary summary is as follows:

  1. el-upload custom upload method
  2. Pictures uploaded to Qiniuyun
  3. Pictures are compressed and uploaded (compressed use) lrz)
  4. Problems not shown in el-upload progress bar

Version information:

  • element-ui 2.3.4
  • vue 2.5.10

Tips:
Because each person does different business, so the code in the article just plays a guiding role, providing a train of thought, specific according to their own needs to adjust.

text

Upload pictures to Qiniuyun

This can only be achieved by front-end and back-end cooperation. Here Is the official JavaScript SDK reference link.

  • Before using JS-SDK, you must register a Qiniu account and login to the console to get a pair of valid Access Key and SecretKey, which you can read. Quick Start and Security mechanisms To further understand how to use and manage keys correctly.
  • JS-SDK relies on service-side token issuance, which can be implemented in two ways:

    1. utilize Seven Cattle Service SDK Building back-end services
    2. Using Qiniu underlying API to build services, see Qiniu for details Upload strategy and Upload vouchers

The front end requests token information through the interface

The front end needs to get the token generated by the back end before uploading the picture.

Custom upload, compressible before upload

The http-request attribute can override the default upload behavior and customize the implementation of the upload.
Look at the code implementation of this custom function:

// Customized Upload Implementation Function
handleHttpRequest(req) {
  // uid is used as a unique identifier to facilitate accurate replacement of image url after uploading
  const uid = req.file.uid 
  // Functions to get file suffix names
  const ext = getFileExt(req.file.name) 
  // Custom key, which is used to rename images when uploading
  let keyname = this.$formatDate(new Date(), 'yyyyMMddhhmmss') + Math.floor(Math.random() * 1000) + '.' + ext
  // Compressed pictures
  let newFile = null
  lrz(req.file, {
    quality: 0.7
  }).then(rst => {
    // Compression Completion
    newFile = rst.file
    // Create form object and upload parameters required by Qiniu Cloud
    const fileData = new FormData() 
    fileData.append('file', newFile)
    fileData.append('token', this.token)
    fileData.append('key', keyname)
    const config = {
      headers: { 'Content-Type': 'multipart/form-data' },
      // This code solves the problem that the progress bar is not displayed, and belongs to the knowledge of axios. See the reference link at the end of the article.
      onUploadProgress: progressEvent => {
       const percentCompleted = Math.floor((progressEvent.loaded * 100) / progressEvent.total)
       req.onProgress({ percent: percentCompleted })
     }
    }
    // Request Qiniuyun's interface, depending on how you configure it
    // Here action is the request address, fileData is the content of the request, and config is the relevant configuration of http.
    // The official request address can be viewed at https://developer.qiniu.com/kodo/manual/1671/region-endpoint
    axios.post($config[this.bucket].action, fileData, config).then(res => {
      const url = `${$config[this.bucket].domain}/${res.data.key}`
      // Modify url
      this.fileList.forEach((item) => {
        if (item.uid === uid) {
          item.url = url
        }
      })
      req.onSuccess(res)
    }).catch(err => {
      req.onError(err)
    })
  }).catch(err => {
    console.log(err)
  })
}

Compressed pictures

The former artificial wheels are directly used here, and the compression ratio and the size limitation of the picture can be set.

For more details, the address is Here It's also useful in the above code, but the wheel author no longer maintains it.

el-upload progress bar is not displayed

After using the custom upload, I found that the progress bar with el-upload failed to display. This problem has been searched for a long time. At first, I didn't know where to listen for the progress events.

The order in the reference link is the order in which I think.

First, I went to check the official issue, realized that it was the problem of monitoring the process, and then I wondered if Axios had relevant settings. After all, I use Axios to send requests here, so Google searched the keyword "axios upload progress" directly and found some relevant information, that is, config to configure the onUpload Progress function, the specific code is shown in the example above.

Reference link:

  1. How to get progress value from http:request of upload component
  2. One of those found by Google Axios upload programs
  3. Google Axios upload programs found the second

(End)

Topics: Javascript axios SDK Google Vue