preface

File uploading is often encountered in front-end development, and third-party platforms are used to store files in most cases. Tencent Cloud COS is commonly used by us. This article is to take me from the front end of Tencent cloud COS storage. This article refers to the Tencent Cloud COS development document JavaScript SDK

steps

  • Install SDK required for Tencent Cloud COS upload

Download cos-js-SDK-v5.min.js and import index.html

  • Listen for the file upload component
// Monitor file changes document.getelementById ('file').onchange = function() {
                    let file = this.files[0];
                    let typeInitUploadObj (that, file.name, file,'image'.function(res) {
                        if (res.success) {
                            that.$message.success(res.msg)
                        } else {
                            that.$message.warning(res.msg)
                        }
                    })
                }
Copy the code
  • Initialize the file upload object (wrapper can also be used for uploading elsewhere)
/** * Initializes the uploaded file object * @param {object} Vue * @param {string} fileName File name * @param {object} file Information about the uploaded file flow and file type * @param {Array} File types allowed to upload * @param {function} uploadStatusCallbalck
 * @return {function} returns the callback function */export const initUploadObj = function (Vue,fileName,file,type,uploadStatusCallbalck) {
  let fileInfo = {
    file_name: fileName,
    media_type: 2,
    media_sub_type: 0,
    size_of_bytes: 122,
    file_expired_type: 'permanent'}; // The front end does the file type restrictionif(type= ='image') {type = ['.jpg'.'.gif'.'.jpeg'.'.bmp'.'.png']}if(type= ='excel') {type = ['.xlsx']}let fileType =file.name ? file.name.substring(file.name.lastIndexOf(".")).toLowerCase() : ' '; 
  if(!!!!!type && type.indexOf (fileType) < 0) {
    uploadStatusCallbalck ({success: false, msg: 'Please upload the correct one'+type+'File format! '});
    return;
  }
  var cos = new COS ({
    getAuthorization: function (options, callback) {
      let singleInfo = Vue.$store.state.fileToken; callback ({ TmpSecretId: singleInfo.tmpSecretId, TmpSecretKey: singleInfo.tmpSecretKey, XCosSecurityToken: singleInfo.sessionToken, ExpiredTime: singleInfo.expiredTime, }); }}); fileInfo.file_name = file.name; GetFileToken (Vue, fileInfo, cos, file, uploadStatusCallbalck); };Copy the code
  • Obtain file upload key (preferably in the backend through Ajax request, high security)
function getFileToken (Vue, fileInfo, cos, file, uploadStatusCallbalck) {
  let url = process.env.VUE_APP_URL + '/file/secretid';
  if(! file)return; Axios.get (url).then (function (res) {
      if(res.data.code == 100000) {// The obtained temporary key is stored in Vue in vuex.$store.commit ('UPDATE_FILE_INFO', res.data.data);
        uploadFile (cos, file, res.data.data, uploadStatusCallbalck);
      } else {
        uploadStatusCallbalck ({success: false, msg: 'Failed to get file key! '});
      }
    })
    .catch (function (err) {
      uploadStatusCallbalck ({success: false, msg: 'Error getting file key interface! '});
    });
}
Copy the code
  • Upload a file (call the relevant API putObject to upload a file)
/**
 * @method uploadFile
 * @param {object} cos
 */
function uploadFile (cos, file, signInfo, callback) {
  cos.putObject (
    {
      Bucket: process.env.VUE_APP_BUCKET,
      Region: 'ap-shanghai',
      Key: signInfo.fileId,
      Body: file,
      onHashProgress: function (progressData) {
        console.log ('Checking', JSON.stringify (progressData));
      },
      onProgress: function (progressData) {
        console.log ('up in', JSON.stringify (progressData)); }},function (err, data) {
      if (err) {
        console.log (err);
        callback ({success: false, msg: 'File upload failed! '});
        return;
      }
      callback ({success: true, msg: 'Upload successful! ', data: data, signInfo: signInfo}); }); }Copy the code

conclusion

Tencent cloud COS file upload is actually divided into three steps, local form processing file flow => obtain relevant parameters according to the document => upload the file.

  • The first step is the processing of the main front-end upload function, which can be used to limit the file upload size (not exactly, according to the byte stream length of the file), file upload type (according to the file suffix name).
  • Most of the parameters for the second step are available in the background of the COS account. This parameter is best stored safely in the background.
  • Step 3 upload We just need to call the SDK related interface to pass in the parameters. Most upload problems can be solved by familiarizing yourself with these three steps.