The effect

  • Asynchronous upload can be done
  • Realize the upload progress of each file
  • The main reason is fast reading and writing speed

1. Create a token interface on the back-end

  • Express is used here

  • node.js SDK

Install the Qiniu module first

npm install qiniu -D

Create qiniu.js to obtain the token

qiniu.js

/** ** */ 
import qiniu from "qiniu";
const AK =  'since you'// In the personal center
const SK = 'your SecretKey'
const bucket = 'look-for'// Space name
// MAC address of the authentication object
const mac = new qiniu.auth.digest.Mac(AK, SK)
// Get the upload token
const options = {
  scope: bucket,
  expires: 3600 * 24 // Expiration time
}
const putPolicy = new qiniu.rs.PutPolicy(options)
const uploadToken = putPolicy.uploadToken(mac)// This is the token we obtained. The backend uses the interface to transmit the token to the front-end

export default uploadToken
Copy the code

2, the front end of the picture to seven cattle cloud space

  • Get what the server just gotuploadToken
  • throughuploadTokenUpload!
  • javascript-SDK
  • Github (recommended)
NPM I qiniu-js -d // Install qiniu SDKCopy the code

This is a fileList file object, and I’m using a Vant component

code

import * as qiniu from 'qiniu-js'
const fileList = [...] // Here is the list of file objects that the front end gets
const uploadToken = 'xxx'// Get the 'uploadToken' from the server
fileList.forEach(i= >{
  //
  const qiniuUploadInfo = {
    file: i.file, // File object
    key: i.file.name, // File resource name
    token: uploadToken, // uplodaToken from the backend
  }
  const putExtra = {
    fname: i.file.name, // The original file name
    params: {}, // Use to place custom variables
    mimeType: null // Specifies the type of files to be uploaded. If the value is null, the file type is not limited. eg: ["image/png", "image/jpeg"]
  }
  const config = {
    useCdnDomain: true./ / the CDN acceleration
    region: qiniu.region.z2 / / area
  }
  const observable = qiniu.upload(
      qiniuUploadInfo.file,
      qiniuUploadInfo.key,
      qiniuUploadInfo.token,
      putExtra,
      config
  )
  // Upload started
  observable.subscribe({
    next(res){
      console.log('next', res)
    },
    error(err){
      console.log('err', err)
    },
    complete(res){// The upload is successful.
      console.log('complete', res)
    }
  })
})
Copy the code