在JavaScript中下载PDF Blob时出现问题 [英] Problem downloading a PDF blob in JavaScript
问题描述
我创建了一个带有blob
和fileName
的函数,该函数应该下载实现如下的blob:
I've created a function that takes a blob
and fileName
which is supposed to download that blob implemented as follows:
const blobToBase64 = (blob, callback) => {
const reader = new FileReader();
reader.onloadend = () => {
const base64 = reader.result;
console.log({ base64 });
callback(base64);
};
reader.readAsDataURL(blob);
};
const downloadFile = (blob, fileName) => () => {
const link = document.createElement('a');
blobToBase64(blob, (base64) => {
link.href = base64;
link.download = fileName;
link.click();
});
};
downloadFile(myBlob, myFileName);
要尝试调试,我做了一个console.log
来注销由reader.result
创建的base64
的值.
To try debug this I've made a console.log
to log out the value of base64
which is created by reader.result
.
该base64
值为data:application/octet-stream;base64,Mzc4MDY4...
我的PDF文件已下载,但已损坏.我的文件下载实现中发生了什么错误?
My PDF file get's downloaded but it's corrupted. What am I doing wrong in my file download implementation?
让我知道是否还有其他细节可能对此有所帮助?我100%确信Blob本身不是损坏的文件.
Let me know if there are any additional details that might help with this? I'm 100% sure that the blob itself is not a corrupted file.
推荐答案
我无法确定您的代码为何无法正常工作,但是我可以确定您的操作充其量是无用的.
I can't tell for sure why your code doesn't work, but I can tell for sure that what you are doing is useless at best.
请勿在99%*的时间内将Blob转换为dataURI ,您可以使用原始Blob和blobURI直接完成此dataURI的操作.
Do not convert a Blob to a dataURI, 99%* of the time, what you want to do with this dataURI can be done directly with the original Blob and a blobURI.
*剩下的1%是需要创建包含二进制数据的独立文档时发生的,但这种情况并不常见.
在这里,您可以再次直接使用Blob完成您想要做的事情(设置锚点以指向Blob的数据):只需调用 URL.createObjectURL(blob)
.
Here, once again what you want to do (set an anchor to point to your Blob's data) can be done with the Blob directly: simply create a blobURI (which is just a pointer to the data in memory) by calling URL.createObjectURL(blob)
.
const downloadFile = (blob, fileName) => {
const link = document.createElement('a');
// create a blobURI pointing to our Blob
link.href = URL.createObjectURL(blob);
link.download = fileName;
// some browser needs the anchor to be in the doc
document.body.append(link);
link.click();
link.remove();
// in case the Blob uses a lot of memory
setTimeout(() => URL.revokeObjectURL(link.href), 7000);
};
downloadFile(new Blob(['random data']), "myfile.txt");
这篇关于在JavaScript中下载PDF Blob时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!