带文件返回的Ajax发布 [英] Ajax post with a file return

查看:84
本文介绍了带文件返回的Ajax发布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有办法返回从ajax帖子结构中获取的动态服务器端生成的文件?

Is there a way to return a dynamically server-side generated file, which was fetched from a ajax post structure?

编写一个小型Web MVC项目,该项目生成一个数据列表(该数据是从复杂的聚合查询生成的,不能从id或任何形式调用),并且涉及到我要导出某些选定内容的部分零件并下载到文件.

Writing a small web mvc project, which generates a list of data(the data is generated from a complex aggregation query and cannot be called from id or whatsoever), and come up to the part on which i want to export some selected parts to a file and download it.

它是如何工作的: 1.在页面上,我选择一些包含关键数据的字段(使用JQuery DataTable) 2.发送给控制器(准确地说是弹簧) 3.生成一个字节流,并将其作为带有"Content-disposition","attachment"标头的HTTPResponse返回.

How does it work: 1. On the page i select some fields with key data(using JQuery DataTable) 2. Send it to a controller(Spring to be precise) 3. Generate a bytestream and return it as a HTTPResponse with "Content-disposition", "attachment" header.

问题是,我使用JQuery-> Ajax选择行并形成所需的数据,因此Controller-> Post的结果保留在javascript部分内,而没有给我另存为...".

Thing is that i select the lines and form the needed data using JQuery->Ajax, so the result of the Controller->Post stays inside the javascript part, not giving me a "Save as...".

我已经在考虑一个临时目录之类的东西,但是要保存最后一个目录.

I'm already thinking of a temporary directory or something, but saving option for the last.

推荐答案

不幸的是,您无法通过ajax获取文件,但是可以通过动态生成表单并提交来实现.根据我们对生成表单并提交表单的评论讨论,您可以执行以下操作.

Unfortunately you can not get file through ajax, but you can achieve it by generate form dynamically and submit it. As per our comment discussion for generate form and submit it you can do something like this.

function autoSubmitForm(method, url, post_data) {
    var element = document.getElementById("virtual_form");
    if(element != null )
    {
        element.parentNode.removeChild(element);
    }
    var form = document.createElement("form");
    form.setAttribute("id", "virtual_form");
    form.setAttribute("style", "display:none;");
    form.method = method;
    form.action = url;   
    for(i in post_data)
    {
         var element=document.createElement("input");
         element.value=post_data[i];
         element.name=i;
         form.appendChild(element); 
    }
    document.body.appendChild(form);
    form.submit();

}

autoSubmitForm('POST','your_url.php',{id:"xyz",other_input:"input value"});

此处{id:"xyz",other_input:"input value"}是发布数据的对象,您可以动态地将其定义为字段名称和字段值对.将其传递给函数.

Here {id:"xyz",other_input:"input value"} is object of post data you can define it dynamically pair of field name and value of field. pass it in function.

这篇关于带文件返回的Ajax发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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