2021-04-12 OSS上传的使用

utils/index.js
/**
   * 获取文件后缀
   * */
export function getSuffix (filePath) {
  return `.${filePath.split('.').pop()}`
}
/**
   * 随机数
   * */
export function random (len) {
  let s = ''
  while (s.length < len) {
    const r = Math.random()
    s += (r < 0.1 ? Math.floor(r * 100) : String.fromCharCode(Math.floor(r * 26) + (r > 0.5 ? 97 : 65)))
  }
  return s
}
import { toast, random, getSuffix } from '@/utils/index'
import OSS from 'ali-oss'
let fileList = []
// 获取oss信息
fileToken({ privateBucketName: false }).then(({ code, data, msg }) => {
        if (code) return
        ossData = data
        // OSS初始化
        client = new OSS({
          region: 'oss-cn-hangzhou',
          accessKeyId: data.accessKeyId,
          accessKeySecret: data.accessKeySecret,
          bucket: data.bucketName,
          stsToken: data.securityToken,
          refreshSTSToken: 1617022351
        })
      })
// 上传
function uploadFile(file) {
      const objectKey = ossData.directory + random(18) + getSuffix(file.file.name)
      try {
        client.put(objectKey, file.file)
          .then(result => {
            fileList.push({ url: result.url })
            emit('update:value', fileList.value)
          })
      } catch (e) {
        toast(`${file.file.name}${t('i18n_upload_pic_tips_02')}`)
      }
    }

你可能感兴趣的:(2021-04-12 OSS上传的使用)