有时需要将网上的图片转存到自己的七牛云,避免网络资源失效。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const qiniu = require("qiniu");
var accessKey = "你的 ak";
var secretKey = "你的 sk";
var bucket = "你的 bucket";
var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
var config = new qiniu.conf.Config();
// 空间对应的机房 华东
config.zone = qiniu.zone.Zone_z0;
var bucketManager = new qiniu.rs.BucketManager(mac, config);
/**
*
* @param {String} _url 网络图片地址
* @param {String} _key 上传后叫啥名
* @returns {String} 七牛云的链接地址
*/
export async function uploadAvatarToQiniu(_url, _key) {
let res = await resToQiniu(_url, bucket, _key);
return "https://usercontents.authing.cn/" + res.data.key;
}

function resToQiniu(resUrl, bucket, key) {
return new Promise((resolve, reject) => {
bucketManager.fetch(resUrl, bucket, key, function(err, respBody, respInfo) {
if (err) {
reject(err);
//throw err;
} else {
if (respInfo.statusCode == 200) {
resolve({ code: 200, data: respBody });
} else {
reject({ code: respInfo.statusCode, data: respBody });
}
}
});
});
}

// (async () => {
// let res = await uploadAvatarToQiniu('https://developer.qiniu.com/assets/android@2x-3522db9ece087f177f28996c410b098e60575ede6bec2073634cc183c686d417.png', 'goodgood.png')
// console.log(res)
// })()