是否可以使用JavaScript生成保存文件对话框? [英] Is it possible to generate a save file dialog using JavaScript?
问题描述
我正在使用jquery ajax将一些数据发布到服务器.服务器发出一个文件(如果请求成功).我只是想知道如何在给定结果的情况下在成功回调中启动保存文件对话框?谢谢.
I am posting some data to the server using jquery ajax. The server spews out a file (if the request is successful). I am just wondering how to initiate the save file dialog within the success callback given the results? Thanks.
PS:
最简单的解决方案是:
$('#ExportToExcel').click(function () {
$('#form').attr({ action: 'bla' });
$('#form').submit();
return false;
});
推荐答案
可以让浏览器根据您的情况提供保存文件"对话框,是的,结合使用JavaScript,服务器响应以及浏览器对该响应的处理.
It is possible to ask the browser to offer the Save File dialog in your situation, yes, with a combination of JavaScript, the server response, and the handling of that response by the browser.
方法如下:
- 创建一个表单以
POST
将数据发送到服务器. - 使用唯一的名称创建隐藏的
iframe
. - 将表单的
target
设置为iframe
的名称. - 发送表单(例如
formElement.submit()
). - 让服务器使用
Content-Disposition
标头和值attachment
进行响应.这是对浏览器的建议,应该保存结果而不是在浏览器本身中显示结果.
- Create a form to
POST
the data to the server. - Create a hidden
iframe
with a unique name. - Set the form's
target
to be the name of theiframe
. - Send the form (e.g.,
formElement.submit()
). - Have your server respond using the
Content-Disposition
header with the valueattachment
. This is a suggestion to the browser that the result should be saved rather than displayed in the browser itself.
If you want to get really fancy, you can use the cookie trick I describe in this other answer so you can get notification when the response is received (whether the server responds with the requested data, or an error). I use that very successfully in a browser-based DHML+JavaScript application where the user can request a custom PDF, and choose to either view it in a browser window (in which case I have the server include the Content-Disposition: inline
header) or save it as a file (Content-Disposition: attachment
).
这篇关于是否可以使用JavaScript生成保存文件对话框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!