我正在使用 Google Drive v3 REST API 開發備份系統。我將 sqlite 備份檔案上傳到 Google Drive 上的檔案夾。這樣可行。我能夠上傳并列出檔案夾中的檔案。
所以現在我正在努力在我的應用程式中恢復該檔案。但是當我下載檔案并寫入回應流時,我最終得到了一個損壞的資料庫檔案。當我在記事本 中打開它時,我看到任何特殊字符(例如 ^ 等)都是正方形,并且檔案比上傳的檔案大 2 mb。
我已經在這里呆了兩天了,無法弄清楚為什么檔案沒有寫入下載內容的 1:1 副本
這是我當前的下載代碼..
async restoreGoogleDriveDatabase(fileId){
const url = encodeURI(`https://www.googleapis.com/drive/v3/files/${fileId}?alt=media`);
const options = {
method: 'GET',
headers: {
'Authorization': 'Bearer ' this.getToken()
},
}
await fetch(url, options).then(async response => response.text())
.then(arrayBuffer => {
const path = require('path').join(window.process.env.ProgramData, 'Home Inventory');
fs.writeFile(`${path}\\HomeInventory1.db`, arrayBuffer, function () {
console.warn('file created');
});
});
},
尋找任何能讓我重回正軌的幫助。
uj5u.com熱心網友回復:
問題似乎與字符編碼有關
最簡單的解決方法是將結果作為 arrayBuffer 獲取,并使用“二進制”編碼寫出 arrayBuffer
像這樣
const fs = require('node:fs/promises');
async restoreGoogleDriveDatabase(fileId) {
const url = encodeURI(`https://www.googleapis.com/drive/v3/files/${fileId}?alt=media`);
const options = {
method: 'GET',
headers: {
'Authorization': 'Bearer ' this.getToken()
},
}
try {
const response = await fetch(url, options);
const arrayBuffer = await response.arrayBuffer();
const path = require('path').join(window.process.env.ProgramData, 'Home Inventory');
await fs.writeFile(`${path}/HomeInventory1.db`, Buffer.from(arrayBuffer, "binary"));
console.warn('file created');
} catch (err) {
console.error(err);
}
},
上面的代碼正確地使用了 async/await,并且還使用fs/promises了而不是fs,因為已經使用了使用 Promise 版本的方法async/await是有意義的fs
重要的變化是
response.arrayBuffer()
將回應作為arrayBuffer
并在fs.writeFile使用中
Buffer.from(arrayBuffer, "binary")
將資料“按原樣”寫入檔案
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/530461.html
