是否可以使用JavaScript生成保存文件对话框? [英] Is it possible to generate a save file dialog using JavaScript?

查看:104
本文介绍了是否可以使用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.

方法如下:

  1. 创建一个表单以POST将数据发送到服务器.
  2. 使用唯一的名称创建隐藏的iframe.
  3. 将表单的target设置为iframe的名称.
  4. 发送表单(例如formElement.submit()).
  5. 让服务器使用Content-Disposition标头和值attachment进行响应.这是对浏览器的建议,应该保存结果而不是在浏览器本身中显示结果.
  1. Create a form to POST the data to the server.
  2. Create a hidden iframe with a unique name.
  3. Set the form's target to be the name of the iframe.
  4. Send the form (e.g., formElement.submit()).
  5. Have your server respond using the Content-Disposition header with the value attachment. 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屋!

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