最近項目中有這麼一個需求,因爲咱們用的騰訊直播軟件(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了好久才發現,測試域名不能用於私有空間和自定義域名必須開啓回源鑑權。按照官網配置便可。測試