最近项目中有这么一个需求,因为咱们用的腾讯直播软件(TClass,腾讯云互动课堂)老师录制的视频存储在腾讯那边,可是腾讯保存视频只有三天有效期,所以,咱们须要抓取视频到咱们的七牛云上面,要求低频存储,要求存储到私有空间。node
const qiniu = require('qiniu'); const accessKey = 'your accessKey'; const secretKey = 'your secretKey'; let mac = new qiniu.auth.digest.Mac(accessKey, secretKey); let config = new qiniu.conf.Config(); config.zone = qiniu.zone.Zone_z0; let bucketManager = new qiniu.rs.BucketManager(mac, config); let resUrl = 'https://blog.adityasui.com/_nuxt/img/user.85831cd.jpg'; let bucket = 'cris-store'; let key = 'sync.png'; bucketManager.fetch(resUrl, bucket, key, function (err, respBody, respInfo) { if (err) { console.log(err); } else { if (respInfo.statusCode === 200) { console.log(respBody.key); console.log(respBody.hash); console.log(respBody.fsize); console.log(respBody.mimeType); } else { console.log(respInfo.statusCode); console.log(respBody); } } });
第三方资源抓取json
可是同步抓取第三方资源的方式不支持不能传递参数,所以不能知足咱们低频存储的需求,而异步抓取第三方的资源是支持传递参数的api
const qiniu = require('qiniu'); const accessKey = 'your accessKey'; const secretKey = 'your secretKey'; let mac = new qiniu.auth.digest.Mac(accessKey, secretKey); let bucket = 'cris-store'; let resUrl = 'https://blog.adityasui.com/_nuxt/img/user.85831cd.jpg'; let key = 'async.png'; let fetchUrl = "http://api-z0.qiniu.com/sisyphus/fetch"; const reqBody = { url: resUrl, bucket, file_type: 1, // 0:标准存储(默认),1:低频存储,2:归档存储 key, }; const reqBodyStr = JSON.stringify(reqBody); qiniu.rpc.post(fetchUrl, reqBodyStr, { Authorization: qiniu.util.generateAccessTokenV2(mac, fetchUrl, 'POST', 'application/json', reqBodyStr), 'Content-Type': 'application/json', }, function (error, response, body) { try { if (error) throw error; console.log(body); } catch (e) { console.log(e); } } );
其中低频存储只须要传递file_type为1就能够了。app
真的很想吐槽一下七牛的文档,明明API都已经写好了,可是就是没有把API写到文档里async
访问私有资源URL与公开资源URL相比只是增长了两个参数e
和token
,分别表示过时时间和下载凭证,由于七牛已经提供了生成下载凭证的例子,这里直接上代码post
const qiniu = require('qiniu'); const accessKey = 'your accessKey'; const secretKey = 'your secretKey'; let mac = new qiniu.auth.digest.Mac(accessKey, secretKey); let config = new qiniu.conf.Config(); let bucketManager = new qiniu.rs.BucketManager(mac, config); let privateBucketDomain = 'http://qagyyccko.bkt.clouddn.com'; let deadline = parseInt(Date.now() / 1000) + 3600; // 1小时过时 采用Unix时间戳,单位为秒 let privateDownloadUrl = bucketManager.privateDownloadUrl(privateBucketDomain, 'whq.mp4', deadline); console.log('@privateDownloadUrl', privateDownloadUrl);
可是后来又遇到一个问题,就是明明设置有效期20秒后,发现过了20秒,资源仍是能够访问,因而Google了好久才发现,测试域名不能用于私有空间和自定义域名必须开启回源鉴权。按照官网配置便可。测试