使用 jQuery 和 iFrame 下载文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16799483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:49:20  来源:igfitidea点击:

Using jQuery and iFrame to Download a File

javascriptjquery

提问by notlkk

I have the following code to download a .csvfile:

我有以下代码来下载.csv文件:

$.ajax({
    url: urlString,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    cache: false,
    success: function(data) {
        if (data) {
            var iframe = $("<iframe/>").attr({
                src: data,
                style: "visibility:hidden;display:none"
            }).appendTo(buttonToDownloadFile);
        } else {
            alert('Something went wrong');
        }
    }
});

The urlStringis pointing to a Restful service that generates the .csvfile and returns the file path which is assigned to the src attribute for the iFrame. This works for any .csvfiles but I'm having problems with .xmlfiles.

urlString指向到生成RESTful服务.csv文件,并返回其被分配给用于所述iFrame的src属性的文件路径。这适用于任何.csv文件,但我遇到.xml文件问题。

When I use the same code but changing the contentTypeto text/xmland use it for downloading .xmlfiles this doesn't work.

当我使用相同的代码但更改contentTypetext/xml并使用它下载.xml文件时,这不起作用。

Can I use the same approach here for .xmlfiles?

我可以在这里对.xml文件使用相同的方法吗?

UPDATE:

更新:

Thanks to Ben for pointing me to the right direction. It turns out I don't need the ajax call at all. Instead, I can just use the iFrame and its url attribute to call the web service, which will generate the content, add the header (Content-Disposition), and return the stream.

感谢 Ben 为我指明了正确的方向。事实证明我根本不需要 ajax 调用。相反,我可以只使用 iFrame 及其 url 属性来调用 Web 服务,该服务将生成内容、添加标题 ( Content-Disposition) 并返回流。

回答by Redsandro

You can also offer it as a download from a virtual anchor element, even if the data is client-side:

您还可以将其作为从虚拟锚点元素下载的内容提供,即使数据是客户端的:

/*
 * Create an anchor to some inline data...
 */

var url = 'data:application/octet-stream,Testing%20one%20two%20three';
var anchor = document.createElement('a');
    anchor.setAttribute('href', url);
    anchor.setAttribute('download', 'myNote.txt');

/*
 * Click the anchor
 */

// Chrome can do anchor.click(), but let's do something that Firefox can handle too

// Create event
var ev = document.createEvent("MouseEvents");
    ev.initMouseEvent("click", true, false, self, 0, 0, 0, 0, 0, false, false, false, false, 0, null);

// Fire event
anchor.dispatchEvent(ev);

http://jsfiddle.net/D572L/

http://jsfiddle.net/D572L/

回答by Ben D

I'm guessing that the problem is that most browsers will try to render XML in the browser itself, whereas they tend to have no handler for CSV, so they'll automatically default to prompt the user to download the file. Try modifying the headers of the XML file to force the download. Something like (PHP example):

我猜测问题在于大多数浏览器会尝试在浏览器本身中呈现 XML,而它们往往没有 CSV 处理程序,因此它们会自动默认提示用户下载文件。尝试修改 XML 文件的标题以强制下载。类似于(PHP示例):

header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header('Content-Disposition: attachment; filename="some filename"');

That should tell most browsers not to attempt to open the file, but instead to have the user download the file and let the OS determine what to do with it.

这应该告诉大多数浏览器不要尝试打开文件,而是让用户下载文件并让操作系统决定如何处理它。

If you have no power to control headers in the XML file itself, you can try a work-around using a server-side script. Use JS to pass the URL to a server-side script:

如果您无权控制 XML 文件本身中的标头,则可以尝试使用服务器端脚本进行变通。使用 JS 将 URL 传递给服务器端脚本:

//build the new URL
var my_url = 'http://example.com/load_file_script?url=' + escape(path_to_file);
//load it into a hidden iframe
var iframe = $("<iframe/>").attr({
    src: my_url,
    style: "visibility:hidden;display:none"
}).appendTo(buttonToDownloadFile);

and on the server-side (your http://example.com/load_file_scriptscript) you use cURL/file_get_contents/wgets/[some other mechanism of fetching remote files] to grab the contents of the remote file, add the Content-Disposition: attachmentheaders, and printthe code of the original file.

和服务器端(您的http://example.com/load_file_script脚本)使用cURL/ file_get_contents/ wgets/抢远程文件的内容,添加[其它一些获取远程文件的机制]Content-Disposition: attachment标头和print原始文件的代码。