上传图片到阿里云 OSS

1.在 index.html 中引入 OSS。

<script src="http://gosspublic.alicdn.com/aliyun-oss-sdk-4.4.4.min.js" />

2.配置参数说明

1)AWconfig为阿里云图片地址配置,基本结构如下,注意至少要包含一个键名为'aliyunConfig'的对象:

{
  "aliyunConfig": {
    "endpoint": "https://example1.aliyuncs.com/",
    "bucket": "example2-image",
    "url":"https://example3.oss-cn-shenzhen.aliyuncs.com"
  }
}

2) token为请求阿里云服务的唯一token,由后端接口返回,有效期为60分钟,注意此参数必须为一个包含三个指定键名的对象,如下:

{
  accessKeyId: 'accessKeyIdFromAPI',
  accessKeySecret: 'accessKeySecretFromAPI',
  securityToken: 'securityTokenFromAPI',
}

3. 在要使用阿里云上传服务的页面中加载时即进行配置,将上述参数传给config方法,此方法返回闭包函数,因此需要一个变量接收。

this.someFn = new Aliyun().config({
  AWconfig: AWconfig,  
  token: token,  
})

在上传图片的组件中调用someFn方法,如下:

this.someFn(callback, file) // file为上传的事件的file,即event.file

callback为此方法执行后的回调函数,此函数接收两个参数如下:

callback(url, aliyunResult) {
  // url为上传后的已保存在阿里云服务器的图片地址
  // aliyunResult为阿里云服务器返回的response数据,可进行其他操作
}

4.图片如何上传阿里云 OSS,同时也上传到接口

<div class="upload">
  <el-upload
    ref="upload"
    action="placeholder"
    :accept="config.accept"
    :multiple="config.multiple"
    :http-request="handleHttpRequest"
    :show-file-list="false"
    list-type="picture"
    v-for="(item, index) in options"
    :key="index"
  >
    <div class="upload-btn">
      <el-button
      type="primary"
      size="small"
      icon="el-icon-upload"
      @click="handleClickType(item, $event)"
      >
      {{ `${ item.label} (${item.number})` }}
      </el-button>
    </div>
  </el-upload>
</div>

upload 组件中,http-request 函数是覆盖默认的上传行为,可以自定义上传的实现。

handleHttpRequest (param) {
  const $that = this
  this.beforeUploadPicture++
  function callback (url, aliyunResult) {
    $that.calculatorSuccessPicture++
    $that.applyFiles.push({
      'fileId': aliyunResult.name, // 必填
      'fileUrl': url,
      'fileName': param.file.name,
    })
  }
  this.someFn(callback, param.file)  // 上传图片至阿里云 OSS
},

因为上传阿里云数据返回可能会存在异步, 所以用两个变量去控制。

watch: {
  'calculatorSuccessPicture' (newVal) {
    if (newVal === this.beforeUploadPicture && newVal !== 0) {
      this.toUpload() // 将阿里云 OSS 上的信息上传到接口
    }
  },
},

调用上传接口:

toUpload (item) {
  transaction.getUpLoadPickUpLetter({
    fileList: this.applyFiles,
    bizType: this.clickType,
    ...this.uploadParam,
  }).then(res => {
    this.beforeUploadPicture = 0
    this.calculatorSuccessPicture = 0
    this.applyFiles = []
    this.$message.success('上传成功')
    this.getFileList({ ...this.uploadParam, bizTypeArray: [] })
  })
},

5. 异常说明

1) token过期,执行someFn(callback, file)时会返回errorCode == 'aliyun-000',捕捉此异常后需要重新向后端请求获取token

2) 参数异常,config()方法中会先执行校验参数,如果参数不符合规定,将会throw new Error(),可在程序中捕捉此异常

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值