[英]Download base64 encoded file
In React, I uploaded a file using:在 React 中,我使用以下方式上传了一个文件:
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = function() {
let base64data = reader.result;
uploadFile(base64data);
return;
}
This gives me a Base64 encoded text data:application/octet-stream;base64,JVBERi0xLj... This is fine as when I decode 'JVBERi0xLj...' I get the correct text in case of a text file.这给了我一个 Base64 编码的文本数据:application/octet-stream;base64,JVBERi0xLj...这很好,因为当我解码“JVBERi0xLj...”时,如果是文本文件,我会得到正确的文本。
When a download request is made to the server I get the same data back but I'm having a difficulty downloading the file.当向服务器发出下载请求时,我会返回相同的数据,但下载文件时遇到困难。 I receive the same base64 encoded string in the response from the server but unable to open the downloaded file.
我在来自服务器的响应中收到相同的 base64 编码字符串,但无法打开下载的文件。
I have done the following:我做了以下事情:
const blob = new Blob([fetchData], { type: 'application/pdf' })
let url = window.URL.createObjectURL(blob);
let a = document.createElement('a');
a.href = blob;
a.download = 'doc.pdf';
a.click();
Any ideas?有任何想法吗?
Note: The upload file is converted to base64 to avoid any http communication issues.注意:上传文件转换为 base64 以避免任何 http 通信问题。
Solution following your suggestions:根据您的建议解决方案:
let fetchDataModified = `data:application/pdf;base64,${fetchData }`;
let a = document.createElement("a");
a.href = fetchData;
a.download = 'doc.pdf';
a.click();
When converting to Base64 during upload the data type was set to 'application/octet-stream'.在上传期间转换为 Base64 时,数据类型设置为“应用程序/八位字节流”。 However, when downloading I changed that to 'application/pdf' following Vaibhav's suggestion and used createElement instead of createObjectURL and it worked.
但是,在下载时,我按照 Vaibhav 的建议将其更改为“application/pdf”,并使用 createElement 而不是 createObjectURL 并且它有效。 Thank you
谢谢
“data:application/pdf” + the base64 string that you saved into our database “data:application/pdf” + 您保存到我们数据库中的 base64 字符串
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.