1. Element uses Tencent Cloud COS

Official configuration document

1. Vue is configured with Tencent Cloud COS

According to their own needs configuration, I am using the most simple official document configuration method

NPM install cos-js-SDK-V5

(2) Create a new cos.js

// import moment from 'moment'
import { credential } from '@/api/common'
var COS = require('cos-js-sdk-v5')
export const uploadFileOrPic = async (file, fileName) => {
 // In order to ensure the security of bucket data, the parameters of the data bucket need to be passed to you from the back end
 const res = await credential({ bucketKey: 'gas_bucket' })
 const { tmpSecretId, tmpSecretKey, sessionToken, bucketName, region, expiredTime } = res.result
 // Create a bucket instance
 const cos = new COS({
   // This parameter is mandatory
   getAuthorization: (options, callback) = > {
     const obj = {
       TmpSecretId: tmpSecretId,
       TmpSecretKey: tmpSecretKey,
       XCosSecurityToken: sessionToken,
       ExpiredTime: expiredTime (expiration time)// Timestamp, in seconds, for example, 1580000900
     }
     callback(obj)
   }
 })
 // Upload the image
 return new Promise((resolve, reject) = > {
   // Use the simplest putObject method to upload the files you need to upload.
   cos.putObject({
     Bucket: bucketName, / * must * /
     Region: region, /* Specifies the location of the bucket. */ is a mandatory field
     // Key: `${new Date().getTime()}${fileName}`,
     Key: fileName,
     StorageClass: 'STANDARD'.Body: file, // Upload the file object
     onProgress: progressData= > {
       console.log(JSON.stringify(progressData))
     }
   }, (err, data) = > {
     // Save the uploaded cover to the local PC
     resolve(data)
     reject(err)
   })
 })
}
Copy the code

(3) Use of component pages

    <el-upload :disabled="loading" action="#"  list-type="picture-card" :on-remove='removePic'  :on-preview='preview' :on-change="(file, fileList) => {handleChange(file, fileList)}" :before-upload="file => beforeUpload(file)" accept=".jpg,.jpeg,.png,.mov,.mp4" :file-list="refuseRefundOptions.voucherDirs">
       <i v-loading.lock="loading" class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    
   // This is used in element's upload. You can write in the change method or beforeUpload method, depending on the business.
   handleChange (file) {
      this.loading = false
      // Please print the file that you uploaded
      uploadFileOrPic(file, file.name,).then(res= > {
        this.url = `https://${res.Location}`
      }).finally(() = > {
        this.loading = false})},Copy the code

(4) A new problem. If a large file needs to be uploaded, tens or hundreds of meters, then cos will start a network process once uploading starts, and it takes time to upload. If you don’t want to upload at this time, JS cannot provide a method to interrupt the COS network process. How to do?

Tencent Cloud COS provides a professional method —-cos.uploadFile

Realization principle:

  • If the size of an uploaded file is smaller than one size, the file is uploaded normally. If the size is larger than one size, the file is fragmented and uploaded automatically

  • Once the project uses shard uploads, cos’s onTaskReady method returns a taskId,

  • CancelTask (taskId) can be used to interrupt your upload process.

An improved version of cos.js

// import moment from 'moment'
import { credential } from '@/api/common'
var COS = require('cos-js-sdk-v5')
export const uploadFileOrPic = async (file, fileName, callBackUp) => {
  const res = await credential({ bucketKey: 'gas_bucket' })
  const { tmpSecretId, tmpSecretKey, sessionToken, bucketName, region, expiredTime } = res.result
  const cos = new COS({
    // This parameter is mandatory
    getAuthorization: (options, callback) = > {
      const obj = {
        TmpSecretId: tmpSecretId,
        TmpSecretKey: tmpSecretKey,
        XCosSecurityToken: sessionToken,
        // StartTime: data. StartTime, // StartTime stamp, in seconds
        ExpiredTime: expiredTime // Expiration timestamp, in seconds
      }
      callback(obj)
    }
  })
  // Upload the image
  return new Promise((resolve, reject) = > {
    cos.uploadFile({
      Bucket: bucketName, / * must * /
      Region: region, /* Specifies the location of the bucket. */ is a mandatory field
      Key: fileName, / / file name
      StorageClass: 'STANDARD'.// Upload type, optional
      Body: file, // Upload the file object
      onTaskReady: function(taskId) {
        // Used to interrupt the call back on the fragment
        callBackUp && callBackUp({cos,taskId})
      },
      onProgress: function (progressData) {
        console.log(JSON.stringify(progressData));
      },
      onFileFinish: function (err, data, options) {
        console.log(options.Key + 'upload' + (err ? 'failure' : 'complete')); }},(err, data) = > {
      // Save the uploaded cover to the local PC
      resolve(data)
      reject(err)
    })
  })
}
Copy the code

Add a new callBackUp callback address to the uploadFileOrPic method, which is used to call taskId from cos

Call callBackUp && callBackUp({cos,taskId}) to the taskId and cos instances

Why return the COS instance to the component? Because the interrupt method cancelTask is only available to cos instances, not your own components

Improved version component. Vue

HandleChange (file) { UploadFile (file, name, TaskRes => {taskId this.currTask = taskRes}). Then (res => {this.url = `https://${res.Location}` }).finally(() => { this.loading = false }) },Copy the code

The value returned by the taskRes callback is the cos instance and taskId we passed out of cos.js so that the component can call cos.cancelTask(taskId) directly at any time to interrupt the upload

2. Cross-domain background configuration of Tencent cloud

Sometimes we configure everything in the code, but still can’t upload, the console reports a cross-domain error. At this time in Tencent cloud to configure the domain name of the project can be.

  1. Log in to Tencent Cloud to find the object storage management background

  1. Find the cross-domain COS configuration and add the rule (origin, use the domain name of the current project, local, test, and online)

Such as:

 *.xxx.com
 http:/ / 127.0.0.1: *
 http://localhost:*
Copy the code

Check all operation methods

Try again is it ok to upload

3. Tencent cloud background configures Referer whitelist

Sometimes after uploading, the link returned to you with cos cannot be opened directly in the newly opened browser TAB because the Referer whitelist needs to be set

The Refer text box will write the domain name of the project you want to open

Empty refer allows null, and blank labels can also be opened

Upload video thumbnail display

There was such a requirement during the development process. The product required the use of Element’s Upload component to support video and picture uploading and preview. There was no problem with picture uploading. The thumbnail can be displayed normally, but after the video is uploaded, the thumbnail cannot be displayed. In this case, it is necessary to intercept the first frame of the video link returned by COS as the first frame display.

Usually return the video link: https://xin-test-1257039795xxxxx/xxxx/xxxxx.mp4

Simply concatenate a string at the end of the link to capture the first frame and display the thumbnail at Element

https://xin-test-1257039795xxxxx/xxxx/xxxxx.mp4?x-oss-process=video/snapshot, t_10000 m_fast (official ali string)

or

https://xin-test-1257039795xxxxx/xxxx/xxxxx.mp4?ci-process=snapshot&time=1 (tencent official string) cos video the first frame documentation

Element uses Ali Cloud OSS

The COS configuration of Aliyun is almost the same as that of Tencent Cloud. It can be done according to the official website configuration (aliyun has more information online).

npm install ali-oss

1. Vue configures ali Cloud OSS

oss.js

This is the configuration of our project, which can meet the basic functions. It is not recommended to use better and more elegant ones.

import moment from 'moment'
import { ossToken } from '.. /api/common'
let OSS = require('ali-oss')
// isStamp adds a time stamp to avoid overwriting files with the same name
export const uploadFile = async (file, fileName, type = 'other', isStamp = true) = > {const res = await ossToken({ bucketName: 'weber-imgs' })
  const { accessKeyId, accessKeySecret, securityToken } = res.result
  let client = new OSS({
    accessKeyId: accessKeyId,
    accessKeySecret: accessKeySecret,
    stsToken: securityToken,
    bucket: 'weber-imgs'.region: 'oss-cn-beijing'.secure: true
  })
  try {
    let env = 'test'
    if (process.env.VUE_APP_ENV === 'production') {
      env = 'pro'
    }
    let result = ' '
    if (isStamp) {
      result = await client.put(`ty/hela/${env}/${type}/${moment().format('YYYYMMDD')}/The ${Date.now()}${fileName}`, file)
    } else {
      result = await client.put(`ty/hela/${env}/${type}/${fileName}`, file)
    }
    return result
  } catch (e) {
    console.log(e)
  }
}

Copy the code

Components use

    // Upload to oss
    async handleChange () {
      this.uploading = true
      try {
        const res = await uploadFile(this.file, this.fileName, 'file'.false)
        if (res.url) {
          / / save the URL
          this.form.iconUrl = res.url
        } else {
          this.$message.error('Upload failed, please try again! ')}}catch (e) {
        this.$message.error('Upload failed, please try again! ')}finally {
        this.uploading = false}},Copy the code

2. Aliyun background configuration is cross-domain

Find ali cloud domain name configuration, the same as COS

3. Aliyun background configures Referer whitelist

Find ali cloud domain name configuration, the same as COS

Upload video thumbnail display

Similarly get the first frame thumbnail

https://xin-test-1257039795xxxxx/xxxx/xxxxx.mp4?x-oss-process=video/snapshot, t_10000 m_fast (official ali string)