Vue front-end Alibaba cloud alioss direct file transfer

1. There is no need to install the Alibaba Cloud plug-in

1. The backend needs to return the configuration information of Alibaba Cloud

2. Front-end Vue code implementation

Need to install js-md5 and axios plugins

<el-upload
  class="upload"
  ref="upload"
  action=""
  :on-change="upload"
  accept="image/png, image/jpeg, image/jpg"
  :show-file-list="false"
  :auto-upload="false"
>
</el-upload>
<img :src="imgUrl">

import axios from 'axios'
import md5 from 'js-md5'

data() {
    
    
	return {
    
    
		imgUrl: ''
	}
},
methods: {
    
    
	// 选择文件
    upload(file) {
    
    
      console.log('file--', file);
      const isIMAGE = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png'
      const isLt3M = file.raw.size / 1024 / 1024 < 3
      if (!isIMAGE) {
    
    
        this.showToast('请选择 jpg、png 格式的图片')
        return false
      }
      if (!isLt3M) {
    
    
        this.showToast('图片大小不能超过 3MB')
        return false
      }
      const path = this.aliossConfig.dir + this.genPath(file)
      this.aliOssUpload(this.aliossConfig, file, path).then(res => {
    
    
        console.log('阿里云直传结果--', res);
        if (res.path) {
    
    
          this.imgUrl = res.path
        } else {
    
    
          this.$message.error('头像上传阿里云失败,请联系工作人员')
        }
      })
    },
    /** 阿里云直传 */
    async aliOssUpload(config, file, path, process) {
    
    
      // config:阿里云配置信息,path:文件名
      let form = new FormData()
      form.append('key', path)
      form.append('OSSAccessKeyId', config.accessKey)
      form.append('policy', config.policy)
      form.append('signature', config.sign)
      form.append('file', file)
      const res = await axios({
    
    
        url: config.upload_domain,
        method: 'post',
        headers: {
    
    
          'Content-Type': 'multipart/form-data',
          'Content-Disposition': 'attachment;filename='+ encodeURIComponent(file.name),
        },
        onUploadProgress: function (progressEvent) {
    
    
          if(progressEvent.lengthComputable) {
    
    
            let rate = progressEvent.loaded / progressEvent.total * 100
            rate = rate.toFixed(3)
            rate = parseFloat(rate)
            process && process(rate,progressEvent.loaded,progressEvent.total)
          }
        },
        withCredentials:false,
        data: form,
      })
      let domain = config.domain.replace(/\/$/,'')
      return {
    
    path: `${
      
      domain}/${
      
      path}`}
    },
    /** 文件名加密、随机数处理 */
    genPath(file) {
    
    
      let ext = file.name.match(/\.[^\.]+$/) || ''
      if(ext) {
    
    
        ext = ext[0]
      }
      let filename = md5((Math.random() * 10000000) + '') + ext
      return filename
    },
}

The front-end implementation method here also needs to do some configuration on the back-end. For specific back-end configuration, you can view the Alibaba Cloud documentation;
the signature direct transfer document https://help.aliyun.com/document_detail/31926.html?spm=a2c4g.267439.0. 0.311c4b78YwyQuw

Guess you like

Origin blog.csdn.net/DarlingYL/article/details/130562603