1. When do I need to upload files directly to Tencent Cloud COS bucket from the front end

In most cases, file uploading is the logic of transferring files to the back end, which then processes and uploads them to Tencent cloud.

However, there are also some cases, such as uploading 1000 users to upload 1000 files to the server at the same time, because the uploading of files takes a relatively long time, it will cause congestion. At this time, you need to upload files directly from the front end to Tencent Cloud COS bucket. In this way, 1000 users can call different Tencent cloud upload interfaces through their browsers to ensure performance

2. Specific operations

Tencent Cloud COS official document

This method is applicable to upload functions requiring high encryption ———— The front-end invokes the back-end interface to obtain the temporary key, and the front-end uploads the temporary key to the Tencent Cloud COS bucket. If the encryption level is not high, you can use a permanent key.

Step 1: Install the SDK

Install the environment SDK through NPM: NPM address.


npm i cos-nodejs-sdk-v5 --save

Copy the code

Step 2: Create uploadcos.js.

The goal here is to normalize the code structure, and if you don’t want to go too far, you can write it in a page file.

// Tencent Cloud object storage
import COS from 'cos-js-sdk-v5'
// getCosSign is a request interface to the background, as the case may be. Generally, background information such as the key is returned
import {getCosSign} from '@kms/api/monthReportManagement/index';

import {Message} from 'element-ui'

var config = {
  Bucket: ' '.Region: ' '.Baseurl: ' '.Key:' '
};
export default function upload(file, callback) {
  // let fileUrl = ''
  getCosSign({
        fileName: file.name
  }).then(response= > { // The background interface returns key information
    if (response.success) {
      const resData = response.data
      const credentials = resData.credentials;
         config.Bucket = resData.bucket;
         config.Region = resData.region;
      config.Baseurl = resData.baseurl;
      config.Key = resData.key;
    let uploadFileName = Date.parse(new Date())
    var cos = new COS({
      getAuthorization: function (options, callback) {
        callback({
          TmpSecretId: credentials.tmpSecretId,
          TmpSecretKey: credentials.tmpSecretKey,
          XCosSecurityToken: credentials.sessionToken,
          StartTime: resData.startTime,
          ExpiredTime: resData.expiredTime,
          expiration: resData.expiration,
          requestId: resData.requestId
        })
      }
    })
    cos.putObject({// The simplest upload function is used here. In addition, Tencent cloud also supports shard upload function and so on.
        Bucket: config.Bucket, // Bucket name
        Region: config.Region, / / region
        Key: config.Key, // Image name
        StorageClass: 'STANDARD'.Body: file, // Upload the file object
        onHashProgress: function (progressData) {
          console.log('Checking'.JSON.stringify(progressData));
        },
        onProgress: function (progressData) {
          console.log('up in'.JSON.stringify(progressData)); }},function (err, data) {// The two parameters here are returned by Tencent cloud, data is different from the above data. Just write it.
      // If the data is an object with Location and so on, then the upload is successful.
        if (err) {
          Message({
            message: 'File upload failed, please upload again'.type: 'error',})// this.$message.error(' File upload failed, please upload again ')
        } else {
          let fileUrl = data.Location
          callback(fileUrl)
        }
      }
    )}
   
  })
}
Copy the code

Step 3: Import the upload.js file in the page file and write el-upload

El-upload simplified version:

.vue file HTML section:

  <el-upload
        ref="upload"
        :action="upload_url"
        :before-upload="beforeUpload"
        :file-list="fileList"
        
      >
        <el-button slot="trigger" size="small" type="primary">Select the file</el-button>
      </el-upload>
Copy the code

.vue file js part

/ / data:
upload_url: '/api/major/report/upload'.fileList: [].// methods

 beforeUpload(file) {
  uploadCos(file,res= > {Uploadcos.js (res) {// if uploadcos.js has a return value
         // --> Callback (fileUrl) fileUrl exists.
        if(res){
          this.$message.success('Upload successful')}}}Copy the code

El-upload full version: See the upload component of Element-UI for details

.vue file HTML section:

  <el-upload
        ref="upload"
        :action="upload_url"
        :before-upload="beforeUpload"
        :file-list="fileList"
        :auto-upload="false"
        :limit="1"
        :on-exceed="handleExceed"
        :on-change="handleChange"
        :on-remove="handleRemove"
      >
        <el-button slot="trigger" size="small" type="primary">Select the file</el-button>
        <el-button
          style="margin-left: 10px;"
          size="small"
          type="primary"
          @click="submitUpload(file)"
        >submit</el-button>
        <div slot="tip" class="el-upload__tip">Only PDF/PPTX files can be uploaded, and the maximum size is 10 MB</div>
      </el-upload>

Copy the code

.vue file js part

import uploadCos from '@kms/api/monthReportManagement/uploadCos'

/ / data:
      upload_url: '/api/major/report/upload'.fileList: [].fileTypes: '.ppt,.pptx,.pdf'.file: new File([' '].'.txt', { type: 'text/plain' }),

 // methods: Upload
    submitUpload() {
      if (this.file.name === '.txt') {
        this.$message({
          message: 'No file found, please select again'.type: 'warning'}); }else {
        this.$confirm('Do you want to upload? '.'tip', {
          type: 'warning',
        }).then(() = > {
          this.$refs.upload.submit(); }); }},// File changes Update the file status
    handleChange(file) {
      this.file = file;
    },
    // Handle deletion
    handleRemove(file, fileList) {
      this.file = new File([' '].'.txt', { type: 'text/plain' });
    },

    // Restrict uploads
    handleExceed(files, fileList) {
      this.$message.warning('Current limit to select 1 file, selected this time${files.length}Three files were selected${files.length + fileList.length}A file `);
    },
    // Check before upload
    beforeUpload(file) {
      let _self = this;
      var testmsg = file.name.substring(file.name.lastIndexOf('. ')).toLowerCase();
      if (_self.fileTypes.indexOf(testmsg) < 0) {
        _self.$message({
          message: testmsg + 'Type file cannot be uploaded, please select again'.type: 'warning'});return false;
      }
      let fileTypesArr = _self.fileTypes.split(', ');
      let mpTypes = ['.pdf'.'.pptx'];
      // Check whether the file meets the requirements
      if (fileTypesArr.indexOf(testmsg) < 0) {
        _self.$message({
          message: 'Upload file can only be' + _self.fileTypes + 'format! '.type: 'warning'});return false;
      } else if (mpTypes.indexOf(testmsg) < 0 || file.size / 1024 / 1024 > 10) {
        _self.$message({
          message: 'Upload file is too large, size cannot exceed 10M! '.type: 'warning'});return false;
      } else if (new Date(this.deadTime + "23:59:59") < new Date()) {
        this.$message({
          type: 'warning'.message: 'Upload is prohibited after upload time'});return false;
      } else {
         uploadCos(file,res= > {Uploadcos.js (res) {// if uploadcos.js has a return value
         // --> Callback (fileUrl) fileUrl exists.
        if(res){
          this.$message.success('Upload successful')}})setTimeout(() = > {
          this.$refs.upload.clearFiles();
        }, 1000); }},Copy the code