处理来自阿贾克斯后的文件下载 [英] Handle file download from ajax post

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

问题描述

我有一个JavaScript的应用程序,将AJAX POST请求特定URL。响应可能是一个JSON字符串或者它可能是一个文件(作为附件)。我可以很容易地发现在我的ajax调用Content-Type和内容处置,但一旦我发现,该响应包含一个文件,我如何提供客户端下载呢?我读过一些在这里同样的线程,但他们没有提供我正在寻找的答案。

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?

编辑:

显然,这不能做,但有一个简单的解决方法,所建议的接受的答案。对于任何人谁遇到这个问题,在未来,这里是我如何解决它:

Apparently, this cannot be done, but there is a simple workaround, as suggested by the accepted answer. For anyone who comes across this issue in the future, here's how I solved it:

$.ajax({
    type: "POST",
    url: url,
    data: params,
    success: function(response, status, request) {
        var disp = request.getResponseHeader('Content-Disposition');
        if (disp && disp.search('attachment') != -1) {
            var form = $('<form method="POST" action="' + url + '">');
            $.each(params, function(k, v) {
                form.append($('<input type="hidden" name="' + k +
                        '" value="' + v + '">'));
            });
            $('body').append(form);
            form.submit();
        }
    }
});

因此​​,基本上,只是产生在AJAX请求中使用,并提交了相同的PARAMS一个HTML表单。

So basically, just generate a HTML form with the same params that were used in AJAX request and submit it.

推荐答案

创建一个表单,使用POST方法,提交表单 - 没有必要为一个iframe。当服务器页面响应请求,写文件的MIME类型的响应头,它将present一个下载对话框 - 我这样做的次数

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.

这篇关于处理来自阿贾克斯后的文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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