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

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

问题描述

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

In our application we need to implement following scenario:

  1. 客户端发送请求
  2. 服务器处理请求并生成文件
  3. 服务器返回文件作为响应
  4. 客户端浏览器显示文件下载弹出对话框并允许用户下载文件

我们的应用程序是基于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 线程).因此,我们需要实现更丑陋、更复杂的解决方案,需要构建带有嵌套隐藏字段的 form 的 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.

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

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