weixin_33704234 2016-08-05 12:46 采纳率: 0%
浏览 15

带文件返回的Ajax发布

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

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.

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.

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.

  • 写回答

1条回答 默认 最新

  • 关注

    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"});
    

    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.

    评论

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码