background

Every user of OSS uses the upload service. On the Web, users upload files to the application server on the browser or App, and the application server uploads the files to the OSS. The specific process is shown in the figure below.

The above approach has three disadvantages compared to data direct to OSS:

  • Slow upload: User data must be uploaded to the application server first and then to the OSS. Network transmission time is twice as long as direct transmission to OSS. If user data is transmitted directly to OSS rather than through the application server, the speed is greatly increased. In addition, OSS uses BGP bandwidth to ensure the transmission speed between local operators.
  • Poor scalability: If there are many subsequent users, the application server will become a bottleneck.
  • High cost: Multiple application servers are required. Since OSS upload traffic is free, several application servers can be saved if data is sent directly to OSS instead of through application servers.

The back-end instructions

For server-side signatures, see:

Help.aliyun.com/document_de…

The front-end implementation

For front-end direct pass, please refer to:

Help.aliyun.com/document_de…

Related,
"ali-oss": "^ 6.2.1." "
Copy the code
Defining utility classes
Ali / / in oss
let OSS = require('ali-oss')

/** * data Back end provides data * [accessKeyId] {String} : created through ali cloud console AccessKey. * [accessKeySecret] {String} : Create AccessSecret through Ali Cloud console. * [bucket] {String} : Bucket created through the console or PutBucket. * [region] {String} : indicates the region where the bucket resides. The default region is OSS-CN-Hangzhou. * /
export function client(data) {
  return new OSS({
    region: data.region,
    accessKeyId: data.accessKeyId,
    accessKeySecret: data.accessKeySecret,
    stsToken: data.stsToken,
    bucket: data.bucket
  })
}

/** * Generates random file names * regular eight random characters, with an underscore attached to the timestamp */
export const getFileNameUUID = () = > {
  function rx() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)}return `The ${+new Date()}_${rx()}${rx()}`
}

Copy the code
Create an instance
<template> <div> <! <el-upload v-if="uploadStyle===0" action="" list-type="picture-card" :file-list="fileList" :auto-upload="true"  :on-exceed="handleExceed" :before-upload="handleBeforeUpload" :http-request="handleUploadFile" :on-preview="handleFileCardPreview" :on-remove="handleRemove"> <i class="el-icon-plus"></i> </el-upload> <el-upload v-if="uploadStyle===1" class="upload-demo" action="" list-type="picture" :file-list="fileList" :auto-upload="true" :on-exceed="handleExceed" :before-upload="handleBeforeUpload" :http-request="handleUploadFile" <el-button size="small" type="primary"> </el-button> </el-upload> <el-upload v-if="uploadStyle===2" class="upload-demo" drag multiple action="" :file-list="fileList" :auto-upload="true" :on-exceed="handleExceed" :before-upload="handleBeforeUpload" :http-request="handleUploadFile" :on-preview="handleFileCardPreview" :on-remove="handleRemove"> <i class="el-icon-upload"></i> <div Class = "el - upload__text" > file will drag here, upload or click < em > < / em > < / div > < / el - upload > <! <el-progress v-show="showProgress" :text-inside="true" :stroke-width="15" :percentage="progress" ></el-progress> <! -- <el-dialog :title="dialogFileUrlTitle" :visible.sync="dialogFileUrlVisible" :close-on-click-modal="false" -- <el-dialog :title="dialogFileUrlTitle" :visible.sync="dialogFileUrlVisible" :close-on-click-modal="false" :close-on-press-escape="false" :destroy-on-close="true" append-to-body> <div v-if="dialogFileFormat==='image'"> <img width="100%" :src="dialogFileUrl" alt=""> </div> <div v-else-if="dialogFileFormat==='video'"> <video controls controlslist="nodownload" preload="auto" style="width: 98%; Text-align: center" : SRC ="dialogFileUrl"> </video> </div> <div v-else> <el-alert title=" type="error" center show-icon> </el-alert> </div> </el-dialog> </div> </template>Copy the code
Method of data
import { client, getFileNameUUID } from '@/utils/ali-oss'
// The interface for obtaining back-end authentication depends on the service implementation.
import { getStsPermission } from '@/api/common/common'

export default {
  name: 'AliUpload'.created() {
    this.initialize()
  },
  data() {
    return {
      // Upload Style 0: card Photo wall 1: thumbnail 2: drag upload file
      uploadStyle: 0.// oss uploads the required data objects
      ossData: {},
      // List of files
      fileList: [].// Progress bar display
      showProgress: false.// Progress bar data
      progress: 0.// File parameter form
      fileParams: {
        // The directory to upload
        folder: '/default/'
      },
      // Display upload
      dialogFileUrlVisible: false.dialogFileUrlTitle: ' '.dialogFileUrl: ' '.dialogFileFormat: ' '}},model: {
    event: 'complete'.prop: ' '
  },
  // Component slot
  props: {
    // Upload location
    position: {
      required: true
    },
    // Use styles
    styleType: {},
    // Display the image
    showFile: {
      type: String}},// Data listener
  watch: {
    showFile: {
      handler() {
        this.onShowFile()
      }
    },
    position: {
      handler() {
        this.onPosition()
      }
    }
  },
  methods: {
    /** Component initialization */
    initialize() {
      this.onPosition()
      this.onShowFile()
      this.uploadStyle = this.styleType
    },

    /** showFile */
    onShowFile() {
      console.log('showFileUrl:' + this.showFile)
      if (this.showFile) {
        let url = this.showFile
        let name = 'Click preview file'
        this.fileList = [{ name, url }]
      } else {
        this.fileList = []
      }
    },

    /** position */
    onPosition() {
      if (this.position === ' ' || this.position == null) {
        this.$message({ message: 'Component initialization failed! The lack of [position] '.type: 'warning' })
        return
      }
      switch (this.position) {
        case 'default':
          this.fileParams.folder = '/default/'
          break
        case 'system':
          this.fileParams.folder = '/system/'
          break
        case 'post':
          this.fileParams.folder = '/post/'
          break
        case 'circle':
          this.fileParams.folder = '/circle/'
          break
        case 'newsPicture':
          this.fileParams.folder = '/news/picture/'
          break
        case 'newsVideo':
          this.fileParams.folder = '/news/video/'
          break
        case 'liveGift':
          this.fileParams.folder = '/live/gift/'
          break
        default:
          this.$message({ message: 'Component initialization failed! Unknown [position] '.type: 'warning' })
          return}},/** Before uploading the file */
    handleBeforeUpload(file) {
      this.$emit('upload-success'.false)
      // Load OSS configuration parameters
      return new Promise((resolve, reject) = > {
        getStsPermission().then(response= > {
          this.ossData = response.data
          resolve(true)
        }).catch(error= > {
          this.$message({
            message: 'Failed to load upload configuration! error msg:' + error,
            type: 'warning'
          })
          reject(false)})})},/** The number of files exceeds the limit */
    handleExceed(files, fileList) {
      this.$message({
        message: 'stop! Can't go any further. '.type: 'warning'})},/** File list remove file */
    handleRemove(file, fileList) {
      this.$message({
        message: 'Successfully removed a file ~'.type: 'success'})},/** Click on the uploaded file */ in the file list
    handleFileCardPreview(file) {
      let fileFormat = this.judgeFileFormat(file.url)
      switch (fileFormat) {
        case 'image':
          this.dialogFileUrlTitle = 'Image Preview'
          break
        case 'video':
          this.dialogFileUrlTitle = 'Video Preview'
          break
        default:
          this.$message.error('The current format is${fileFormat}, do not support preview! `)
          return
      }
      this.dialogFileFormat = fileFormat
      this.dialogFileUrl = file.url
      this.dialogFileUrlVisible = true
    },

    /** Determine the file format by URL */
    judgeFileFormat(fileUrl) {
      // Get the last one. The location of the
      const index = fileUrl.lastIndexOf('. ')
      // Get the suffix
      const suffix = fileUrl.substr(index + 1)
      console.log('The current file suffix format is suffix:${suffix}`)
      // Get the type result
      let result = ' '
      // Image format
      const imgList = ['png'.'jpg'.'jpeg'.'bmp'.'gif']
      // Match the image
      result = imgList.find(item= > item === suffix)
      if (result) {
        return 'image'
      }
      / / match TXT
      const txtList = ['txt']
      result = txtList.find(item= > item === suffix)
      if (result) {
        return 'txt'
      }
      / / match excel
      const excelList = ['xls'.'xlsx']
      result = excelList.find(item= > item === suffix)
      if (result) {
        return 'excel'
      }
      / / match the word
      const wordList = ['doc'.'docx']
      result = wordList.find(item= > item === suffix)
      if (result) {
        return 'word'
      }
      / / match the PDF
      const pdfList = ['pdf']
      result = pdfList.find(item= > item === suffix)
      if (result) {
        return 'pdf'
      }
      / / match the PPT
      const pptList = ['ppt'.'pptx']
      result = pptList.find(item= > item === suffix)
      if (result) {
        return 'ppt'
      }
      // Match the video
      const videoList = ['mp4'.'m2v'.'mkv'.'rmvb'.'wmv'.'avi'.'flv'.'mov'.'m4v']
      result = videoList.find(item= > item === suffix)
      if (result) {
        return 'video'
      }
      // Match the audio
      const radioList = ['mp3'.'wav'.'wmv']
      result = radioList.find(item= > item === suffix)
      if (result) {
        return 'radio'
      }
      // Other file types
      return 'other'
    },

    /** Perform file upload */
    handleUploadFile(file) {
      let that = this
      // Select the directory
      let folder = that.fileParams.folder
      // Environmental judgment
      let active = that.ossData.active
      // Officially separated from the test environment storage
      if(active ! = =null&& active ! = =undefined) {
        if (active === 'dev' || active === 'test') {
          folder = '/test' + folder
        }
      }
      // oss-host
      let host = 'https://static.v.xxxxxxxxx.com'

      async function multipartUpload() {
        let temporary = file.file.name.lastIndexOf('. ')
        let fileNameLength = file.file.name.length
        let fileFormat = file.file.name.substring(
            temporary + 1,
            fileNameLength
        )
        // File path and file name concatenate file format
        let fileNameUrl = folder + getFileNameUUID() + '. ' + fileFormat
        client(that.ossData).multipartUpload(fileNameUrl, file.file, {
          progress: function(plan) {
            that.showProgress = true
            that.progress = Math.floor(plan * 100)
          }
        }).then(result= > {
          that.$message({
            message: 'Upload successful'.type: 'success'
          })
          console.log('Upload complete result:' + JSON.stringify(result))
          // Fill in the input box after the file is uploaded successfully
          let uploadResult = host + fileNameUrl
          that.$emit('complete', uploadResult)
          that.$emit('upload-success'.true)
          that.showProgress = false
        }).catch(error= > {
          that.$message({
            message: 'Upload failed! error:' + error,
            type: 'warning'
          })
        })
      }

      multipartUpload()
    }
  }

}
Copy the code

Components use

<el-form-item label=" newsPicture" prop="sImgUrl"> <a8-ali-upload position="newsPicture" :styleType="2" :showFile="saveParams.sImgUrl" v-model="saveParams.sImgUrl"> </a8-ali-upload> <el-input style="margin-top: 10px" v-model=" saveparams.simgurl "placeholder=" newscover link "/> </el-form-item>Copy the code

The above is the specific application of Ali Cloud OSS WEB direct transmission under vue. js.