在Safari中使用blob保存CSV文件 [英] Saving CSV file using blob in Safari

查看:1723
本文介绍了在Safari中使用blob保存CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码生成下载链接,以便用户可以在我的网站上下载.csv文件。

I have codes below to generate the download link so that users could download the .csv file on my site.

var link = document.createElement("a");
link.id = "csvDwnLink";
window.URL = window.URL || window.webkitURL;

var csv = "\ufeff" + CSV,
    blob = new window.Blob([csv], {type: 'text/csv, charset=UTF-8'}),
    csvUrl = window.URL.createObjectURL(blob),
    filename = 'export.csv';

$("#csvDwnLink").attr({'download': filename, 'href': csvUrl});
$('#csvDwnLink')[0].click();
document.body.removeChild(link);

我希望用户可以点击 csvUrl 下载cvs文件。

它适用于chrome。但是,当我使用Safari单击相同的链接,它将直接显示在选项卡中的csv文件的内容。

I hope the user could click the download link with csvUrl to download the cvs file.
It works on chrome. However, when I click the same link using Safari, it will directly show me the content of the csv file in the tab.

如何解决这个问题,以便safari将显示保存文件窗口,用户可以选择他们要保存文件的路径,而不是显示内容cvs文件直接点击下载链接?

希望有人能给我一些建议或替代方法。

提前感谢!

How do I solve this problem so that the safari will show the saving file window which user could select the path where they want to save the file instead of showing the content of the cvs file directly when I click the download link?
Hope someone could me some recommendations or alternative methods.
Thanks in advance!

==已更新==

在此找出解决方案

解决方案1 ​​
解决方案2

代码将是:

var link = document.createElement("a");
link.id = "csvDwnLink";

document.body.appendChild(link);
window.URL = window.URL || window.webkitURL;
var csv = "\ufeff" + CSV,
    csvData = 'data:attachment/csv;charset=utf-8,' + encodeURIComponent(csv),
    filename = 'filename.csv';
$("#csvDwnLink").attr({'download': filename, 'href': csvData});
$('#csvDwnLink')[0].click();
document.body.removeChild(link);

Safari将为用户下载文件,但文件名将为 unknown ,可能是因为Safari不支持下载属性,但 raphael 提到。

Safari will download the file for the user, however, the file name will be unknown, probably it's because Safari don't support 'download' attribute yet as raphael mentioned.

推荐答案

我做了一个快速的研究 - 我看起来Safari不支持你想要实现的。

I did a quick research - I looks like Safari does not support what you are trying to achieve.

您的解决方案在Chrome(和Firefox)中的工作原因是,他们支持下载属性 - Safari doesn尚未。

The reason why your solution works in Chrome (and Firefox) is that they support the download attribute - Safari doesn't yet.

这篇关于在Safari中使用blob保存CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆