我要实现大文件下载(大约10-1024 Mb)。我已经成功从Dropbox获取文件:
operationResult = await dbx.filesDownload({
path: `/${CONFIG_STORAGE.uploader.assetsPath}/${fileUUID}`
});
然后,将接收到的文件与元数据捆绑在一起,然后将其返回到我的Node.js服务器:
fileMIME = mime.lookup(operationResult.name);
const downloadResult = Object.freeze({
fileBinary: operationResult.fileBinary,
fileLength: operationResult.fileBinary.length,
fileMIME,
fileName: operationResult.name,
isSucceeded,
message
});
return downloadResult;
现在Buffer
,我将从Dropbox获得的转换为Readable
流,并将其通过管道返回给客户端:
res.setHeader("Content-Disposition", "attachment; filename=" + downloadResult.fileName);
res.setHeader("Content-Type", downloadResult.fileMIME);
const fileReadableStream = new Readable();
fileReadableStream.push(downloadResult.fileBinary);
fileReadableStream.push(null);
fileReadableStream.pipe(res);
到现在为止,一切都已经清楚并且可以运行了。在这里,我面临第一个陷阱:我需要某种方式来触发浏览器中的下载过程。
在许多示例中,使用了一些小图像或JSON,我们可以将它们完全加载到RAM中,进行操作,例如,转换为Base64
,将其分配给a.href
和触发a.click()
。但是由于我的文件大小为10-50 Mb,所以我不确定这种方法是否正确。
我已经尝试过Fetch API:
const response = await fetch(`${host}/download?fileName=${fileName}`, {
credentials: "same-origin",
method: "POST",
mode: "cors"
});
const a = document.createElement("a");
a.href = response.text();
a.download = "MyFile.pdf";
a.click();
但我总是失败-没有文件错误。我也尝试使用jQuery AJAX和XMLHttpRequest
(XHR
),但仍未下载文件。
也许,我缺少一些东西。如何从服务器获取10-1024 Mb文件?
PS:我从来没有想到过像文件下载这样的琐碎任务会如此复杂。
我已经解决了通过开关从发出filesDownload
到filesGetTemporaryLink
,它返回一个链接到一个文件,而不是文件本身。然后,我触发该链接的下载。
最终结果:
operationResult = await dbx.filesGetTemporaryLink({
path: `/${CONFIG_STORAGE.uploader.assetsPath}/${fileUUID}`
});
const downloadResult = Object.freeze({
fileLength: operationResult?.metadata.size,
fileLink: operationResult?.link,
fileMIME: mime.lookup(operationResult?.metadata.name),
fileName: operationResult?.metadata.name,
isSucceeded,
message
});
return downloadResult;
然后,我将输出发送给客户端:
res.json(downloadResult);
在客户端,我通过await
/ async
Fetch API调用获得它:
const fileResponse = await fetch(``${host}/downloadDocument`, {
body: JSON.stringify({fileUUID: fileName}),
cache: "no-cache",
credentials: "same-origin",
headers: {
"Content-Type": "application/json"
},
method: "POST",
mode: "cors"
});
const fileData = await fileResponse.json();
const aTag = document.createElement("a");
aTag.href = fileData.fileLink;
aTag.download = fileData.fileName;
aTag.click();
结果,无论我要下载的文件大小如何,服务器都根本不需要处理文件,也没有额外的CPU,RAM或流量影响。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句