[英]JavaScript how can I make sure the downloaded file is successful and not corrupted
我正在使用Electron-Node.js ,我正在嘗試從服務器下載文件並將其保存到本地磁盤中。
下面的代碼按預期工作,但我不確定這是否是最好的方法。
<script>
const { ipcRenderer } = require('electron');
var fs = require('fs');
// (2) convert the blob to file.
async function saveBlobToFile(blob, filename) {
let fileData = new Int8Array(await blob.arrayBuffer());
fs.writeFileSync(filename, fileData);
console.log("Blob successfully saved to file.");
//is the file healthy though?
}
// (1) (download the file)
function download(downloadURL, downloadDirectory){
var filename = "test.zip"; //this could be exe, images, pdf
if (!fs.existsSync(downloadDirectory)){
fs.mkdirSync(downloadDirectory, { recursive: true });
console.log("Download Directory doesn't exist, created.");
}
console.log("Downloading...");
fetch(downloadURL)
.then(response => response.blob())
.then(blob => {
console.log("Downloaded and is now saving...");
saveBlobToFile(blob, downloadDirectory+"\\"+filename);
}).catch(console.error);
}
download("https://sample.com/test.zip", "SOME_DIRECTORY_HERE"); //let's try to download the file.
</script>
WhatIF來了;
我用50MB
的文件大小對其進行了測試,它可以工作,文件很健康。 但是如果文件大小超過200MB
或者說是一個large file
並且用戶只有非常有限的互聯網連接怎么辦? 文件可能會損壞,如何避免這種情況? 我們如何檢查或確保文件已成功下載且未損壞?
我在想,也許我可以檢查下載文件的 MD5 校驗和,並將其與來自服務器的文件進行比較。 但這足夠了嗎?
如果 MD5 校驗和與服務器不同,則重新下載文件並重新檢查,但這對於互聯網連接非常有限的用戶來說又是一種數據浪費。
正如馬克所說,您的文件被損壞並沒有常見的原因
但
我在想,也許我可以檢查下載文件的 MD5 校驗和,並將其與來自服務器的文件進行比較。 但這足夠了嗎?
對我來說是你自己問題的書面答案。
然后
如果 MD5 校驗和與服務器不同,則重新下載文件並重新檢查,但這對於互聯網連接非常有限的用戶來說又是一種數據浪費。
好吧,您可以將文件分成幾塊。
如果您有大文件要傳輸(例如 > 1Gb),您可以將其拆分為 100Mb 的塊並逐個傳輸,並單獨檢查校驗和,然后將它們連接起來並再次檢查完整的校驗和。
例如:
Buffer.from(fileParts)
並驗證最終校驗和這只是對您問題的潛在解決方案的快速思考。
希望它可以幫助你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.