为什么threre是没有办法使用ajax请求下载文件? [英] Why threre is no way to download file using ajax request?

查看:124
本文介绍了为什么threre是没有办法使用ajax请求下载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的应用程序中,我们需要实现以下方案:

In our application we need to implement following scenario:


  1. 请求是从客户端发送

  2. 服务器处理请求并生成文件

  3. 服务器返回文件

  4. 客户端浏览器显示文件下载弹出对话框,允许用户下载文件

  1. A request is send from client
  2. Server handles the request and generates file
  3. Server returns file in response
  4. Client browser displays file download popup dialog and allows user to download the file

我们的应用程序是基于ajax的应用程序,因此我们发送ajax请求非常简单方便(如使用 jquery.ajax()函数)。

Our application is ajax based application, so it would be very easy and convenient for us to send ajax request (like using jquery.ajax() function).

但是,googilng之后,原来只有在使用非ajax POST请求时才能进行文件下载(如在这个流行的SO线程)。因此,我们需要实现更为复杂和更复杂的解决方案,需要使用嵌套隐藏字段构建表单的HTML结构。

But after googilng, it turned out that file downloading is possible only when using non-ajax POST request (like described in this popular SO thread). So we needed to implement uglier and more complex solution that required building HTML structure of form with nested hidden fields.

有人可以用简单的话解释为什么ajax请求不能用于下载文件?这是什么机制?

Could someone explain in simple words why is that ajax requests cannot be used to download file? What's the mechanics behind that?

推荐答案

这不是关于AJAX。当然可以使用AJAX下载文件。但是,文件将被保存在内存中,即不能将文件保存到磁盘。这是因为JavaScript无法与磁盘进行交互。这将是一个严重的安全问题,并在所有主流浏览器中被阻止。

It's not about AJAX. You can download a file with AJAX, of course. However the file will be kept in memory, i.e. you cannot save file to disk. This is because JavaScript cannot interact with disk. That would be a serious security issue and it is blocked in all major browsers.

这篇关于为什么threre是没有办法使用ajax请求下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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