封装的七牛云上传图片方法(util.js)
https://developer.qiniu.com/kodo/sdk/1663/legacy-php
转自https://www.cnblogs.com/binli/p/10450674.html
const qiniuUploader = require("./qiniuUploader");
import api from ‘./api.js’;
const getUploadToken = () => {
var params = {
token: wx.getStorageSync(‘token’)
}
api.ajax(“GET”, params, “/weixin/getUploadToken”).then(res => {
console.log(res.data)
initQiniu(res.data)
});
}
// 初始化七牛相关参数
const initQiniu = (uptoken) => {
var options = {
region: ‘NCN’, // 华北区
// uptokenURL: ‘https://[yourserver.com]/api/uptoken’,
// cdn.wutongdaojia.com
// uptokenURL: ‘http://upload-z1.qiniup.com’,
// uptokenURL: ‘https://yuesao.wutongdaojia.com/weixin/getUploadToken’,
// uptoken: ‘xxx’,
uptoken: uptoken,
// domain: ‘http://[yourBucketId].bkt.clouddn.com’,
domain: ‘image.bkt.clouddn.com’, // image为七牛云后台创建的空间
shouldUseQiniuFileName: false
};
qiniuUploader.init(options);
}
export function didPressChooesImage(that, count, callback) {
getUploadToken();
// 微信 API 选文件
wx.chooseImage({
count: count,
success: function(res) {
console.log(res)
var filePath = res.tempFilePaths[0];
console.log(filePath)
callback(filePath)
// 交给七牛上传
}
})
}
/**
- 文件上传
- 服务器端上传:http(s)?/up.qiniup.com
- 客户端上传: http(s)?/upload.qiniup.com
- cdn.wutongdaojia.com
*/
function uploader(file, callback) {
initQiniu();
qiniuUploader.upload(filePath, (res) => {
// 每个文件上传成功后,处理相关的事情
// 其中 info 是文件上传成功后,服务端返回的json,形式如
// {
// “hash”: “Fh8xVqod2MQ1mocfI4S4KpRL6D98”,
// “key”: “gogopher.jpg”
// }
// 参考http://developer.qiniu.com/docs/v6/api/overview/up/response/simple-response.html
that.setData({
‘imageURL’: res.imageURL,
});
}, (error) => {
console.log('error: ’ + error);
},
// , {
// region: ‘NCN’, // 华北区
// uptokenURL: ‘https://[yourserver.com]/api/uptoken’,
// domain: ‘http://[yourBucketId].bkt.clouddn.com’,
// shouldUseQiniuFileName: false
// key: ‘testKeyNameLSAKDKASJDHKAS’
// uptokenURL: ‘myServer.com/api/uptoken’
// }
null, // 可以使用上述参数,或者使用 null 作为参数占位符
(res) => {
console.log(‘上传进度’, res.progress)
console.log(‘已经上传的数据长度’, res.totalBytesSent)
console.log(‘预期需要上传的数据总长度’, res.totalBytesExpectedToSend)
});
};
module.exports = {
initQiniu: initQiniu,
getUploadToken: getUploadToken,
didPressChooesImage: didPressChooesImage
}