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.'
})
},