七牛云调用JS-SDK 上传文件
- 业务需要,使用七牛云存储文件,开始打算在后端实现上传功能,看了官方SDK,相比较前端来处理相对方便些,以下是具体实现。
引入
用的是React框架,使用 NPM 安装:
npm install qiniu-js
import * as qiniu from ‘qiniu-js’
官方给到的方法:
var observable = qiniu.upload(file, key, token, putExtra, config)
var subscription = observable.subscribe(observer) // 上传开始
// or
var subscription = observable.subscribe(next, error, complete) // 这样传参形式也可以
subscription.unsubscribe() // 上传取消
下面是我项目的具体过程:
首先需要一个获取上传token的接口:
/**
* 获取上传凭证
*/
public GetUpTokenOutput getUpToken() {
GetUpTokenOutput outputObj = new GetUpTokenOutput();
Auth auth = Auth.create(cdnConfig.getQiniuAccessKey(), cdnConfig.getQiniuSecretKey());
String uptoken = auth.uploadToken(cdnConfig.getBucket());
log.info(“获取上传凭证qiniuAccessToken=” + uptoken);
outputObj.setUpToken(uptoken);
return outputObj;
}
upload触发的方法:
handleUpload = () => {
const {
fileList } = this.state;
let fileKey = this.state.uploadFileDetail.fileKey;
fileList.forEach(file => {
console.info(file);
});
this.setState({
uploading: true,
});
if (common.functionCommon.isEmpty(fileKey)) {
fileKey = fileList[0].name;
}
this.state.uploadFileDetail.sourceFileKey = fileList[0].name;
this.