后端(Node.js)
后端的作用是为前端提供上传所需要的凭证
准备
注册七牛开发者帐号
登录七牛开发者后台,获取AccessKey 和 Secret Key
创建对象存储的存储空间
地址:https://portal.qiniu.com/user/key
sdk安装
npm install qiniu --save
token生成
let mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
let options = {
scope: config.Bucket,
expires: 7200,
returnBody: '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}'
};
let putPolicy = new qiniu.rs.PutPolicy(options);
let uploadToken = putPolicy.uploadToken(mac);
scope:存储空间的名称
expires:凭证的有效时间,默认情况下,有效期为1个小时
returnBody:返回的内容,上面代码设置返回的JSON格式的内容uploadToken
即为前端上传所需要的token
前端(vue)
sdk安装
//安装
npm install qiniu-js --save
//引入
var qiniu = require('qiniu-js')
// or
import * as qiniu from 'qiniu-js'
上传代码
<a-upload name="file"
:action="qiniuUrl"
:beforeUpload="beforeUpload"
@change="handleChange" :data="{token:qiniuToken}">
</a-upload>
qiniuUrl:存储空间所在的存储区域
https://developer.qiniu.com/kodo/manual/1671/region-endpoint
qiniuToken:从后端获取到的token
beforeUpload(file) {
let that = this
let putExtra = {
fname: file.name,
params: {},
mimeType: ["image/png", "image/jpeg", "image/gif"]
};
let observe = {
next(res) {},
error(err) {},
complete(res) {}
};
let config = {
useCdnDomain: true,
};
let observable = qiniu.upload(file, 'pageapi_' + (new Date()).valueOf() + file.name.replace(/.*\./, '.'), this.qiniuToken, putExtra, config)
observable.subscribe(observe)
},
qiniu.upload(file: blob, key: string, token: string, putExtra: object, config: object)
file: Blob 对象,上传的文件
key: 文件资源名
token: 上传验证信息,前端通过接口请求后端获得
config: object
putExtra:
参考
https://developer.qiniu.com/kodo/sdk/1289/nodejs
https://developer.qiniu.com/kodo/sdk/1283/javascript
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。