问题描述
我用base64创建了一个Blob,我需要将该数据下载为pdf。
I have a blob created with a base64, and I need to make this data downloadable as a pdf.
我创建了以下代码段:
var blob = new Blob([byte]);
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.target = '_blank';
var fileName = name + '.pdf';
link.download = fileName;
link.click();
它适用于所有浏览器,但iOS上的safari mobile除外。
It works on all the browsers, except than safari mobile on iOS.
文件实际上已下载,但名称为未知,由于扩展名丢失,因此无法打开。
The file gets actually downloaded, but its name is "unknown", then it can't be open since the extension gets lost.
问题在于对此浏览器和IE缺乏支持。
The problem is that the download attribute lacks support on this browser and IE.
对于IE,有很多解决方法,但我没有在Safari / iOS中找到任何解决方法。
There are a lot of workarounds for IE, but I didn't find any for safari/iOS.
您知道我该怎么办在此浏览器中下载从base64(不涉及XHR)获得的Blob?
Do you know how can I download a blob got from a base64 (no XHR involved) in this browser?
谢谢
推荐答案
快捷答案:您不能。由于存在此,因此无法在safari iOS上下载文件
SHORT ANSWER: you can't. Due this bug is impossible to download the file on safari iOS
另一种方法是在浏览器上使用正确的mime类型打开文件,以便它可以显示其内容(然后用户可以手动
The alternative is to open the file on the browser with the proper mime type, so it can show its content (and the user can then manually download it if needed).
在创建Blob时,请确保传递mime类型。
Make sure to pass mime type when creating the Blob. reference
var blob = new Blob([byte], {type: 'application/pdf'});
最后,我强烈建议您使用,它可以处理大多数极端情况/多种浏览器对保存的支持(或在这种情况下,请打开)JavaScript中的文件。
Lastly, I'd strongly suggest you to use FileSaver.js which that can handle most of the corner cases/multiple browser support for save (or in this case, open) a file in javascript.
这篇关于Safari / iOS中“下载”属性的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!