vue上传图片至又拍云

2 篇文章 0 订阅

vue项目中上传图片至又拍云使用的是官方的FORM API方法,官方链接:https://help.upyun.com/knowledge-base/form_api/#old-authorization
图片的上传过程中主要用到的参数为file,policy、signature,file这里直接使用的element-ui上传组件。

policy

policy主要参数,参考官方链接:https://help.upyun.com/knowledge-base/form_api/#upload_args。从官方链接中可以看出,policy中主要必填参数为(bucket:文件上传到的服务,即又拍云的服务名称;save-key:文件保存路径,可用占位符;expiration:请求的过期时间,UNIX UTC 时间戳,单位秒。建议设为 30 分钟),其他参数可看情况添加。最终结果需进行转json和Base64处理(Base64编码:window.btoa(str),解码:window.atob(str))。

signature

signature为policy与文件密钥使用&拼接而成,文件密钥可在又拍云-云存储-存储管理-文件密钥处获得,拼接后字符串计算md5为最终结果,这里使用的是CryptoJS的MD5方法。

import CryptoJS from 'crypto-js'

const upyunSignature=()=>{
  let policy=window.btoa(JSON.stringify({
    'bucket': '服务名称',
    'content-length-range': '0,10240000',//文件大小限制
    'save-key': '/{filemd5}{.suffix}',//文件路径
    'expiration': Math.floor(new Date().getTime() / 1000) + 86400//过期时间
  }))
  let signature=CryptoJS.MD5(policy+'&文件密钥').toString()//此处文件密钥前要添加&符号,容易出错
  return {
    policy:policy,
    signature:signature
  }
}

export {upyunSignature}

页面引用:

<el-upload
    ref="upload"
    :show-file-list="false"
    accept="image/png, image/jpeg"
    :max-size="2048"
    class="avatar-uploader"
    :on-success="handleSuccess"
    :on-error="handleFormatError"
    :data="upyunSignature"
    action="//v0.api.upyun.com/服务名称">
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
//js部分
handleSuccess (res) {
  this.imageUrl = this.imageUrl+res.url
  console.log(this.imageUrl);
},
handleFormatError (file) {
  this.$Notice.warning({
    title: 'The file format is incorrect',
    desc: 'File format of ' + file.name + ' is incorrect, please select jpg or png.'
  })
},
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

灬风吹雨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值