处理从 ajax 帖子下载的文件 [英] Handle file download from ajax post

查看:31
本文介绍了处理从 ajax 帖子下载的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 javascript 应用程序,可以将 ajax POST 请求发送到某个 URL.响应可能是一个 JSON 字符串,也可能是一个文件(作为附件).我可以在 ajax 调用中轻松检测 Content-Type 和 Content-Disposition,但是一旦检测到响应包含文件,我该如何提供客户端下载它?我在这里阅读了许多类似的主题,但没有一个提供我正在寻找的答案.

I have a javascript app that sends ajax POST requests to a certain URL. Response might be a JSON string or it might be a file (as an attachment). I can easily detect Content-Type and Content-Disposition in my ajax call, but once I detect that the response contains a file, how do I offer the client to download it? I've read a number of similar threads here but none of them provide the answer I'm looking for.

拜托,拜托,请不要发布暗示我不应该为此使用ajax或应该重定向浏览器的答案,因为这些都不是一个选项.使用纯 HTML 表单也不是一种选择.我需要的是向客户端显示下载对话框.这能做到吗?如何做到?

Please, please, please do not post answers suggesting that I shouldn't use ajax for this or that I should redirect the browser, because none of this is an option. Using a plain HTML form is also not an option. What I do need is to show a download dialog to the client. Can this be done and how?

推荐答案

创建表单,使用 POST 方法,提交表单 - 不需要 iframe.当服务器页面响应请求时,为文件的 MIME 类型写一个响应头,它会显示一个下载对话框 - 我已经做了很多次了.

Create a form, use the POST method, submit the form - there's no need for an iframe. When the server page responds to the request, write a response header for the mime type of the file, and it will present a download dialog - I've done this a number of times.

您想要应用程序/下载的内容类型 - 只需搜索如何为您使用的任何语言提供下载.

You want content-type of application/download - just search for how to provide a download for whatever language you're using.

这篇关于处理从 ajax 帖子下载的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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