使用Javascript / jQuery来通过POST下载文件JSON数据 [英] Javascript/jquery to download file via POST with JSON data

查看:157
本文介绍了使用Javascript / jQuery来通过POST下载文件JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于jQuery的单页Web应用程序。它通过AJAX调用的RESTful Web服务进行通信。

I have a jquery-based single-page webapp. It communicates with a RESTful web service via AJAX calls.

我想完成以下任务:

  1. 在提交包含JSON数据到一个REST的url POST。
  2. 如果请求指定一个JSON响应,然后JSON被返回。
  3. 如果请求指定了一个PDF / XLS /等反应,然后下载的二进制文件返回。

我有1安培; 2现在的工作,并在客户端应用程序的jQuery通过创建基于JSON数据的DOM元素显示在网页中返回的数据。我也有#3从视图web的服务点的工作,这意味着它将创建和如果给正确的JSON参数返回的二进制文件。但我不能确定,处理#3在客户端的最佳方式的javascript code。

I have 1 & 2 working now, and the client jquery app displays the returned data in the web page by creating DOM elements based on the JSON data. I also have #3 working from the web-service point of view, meaning it will create and return a binary file if given the correct JSON parameters. But I'm unsure the best way to deal with #3 in the client javascript code.

是否有可能得到一个可下载的文件重新从这样一个Ajax调用?我如何在浏览器下载并保存文件?

Is it possible to get a downloadable file back from an ajax call like this? How do I get the browser to download and save the file?

$.ajax({
    type: "POST",
    url: "/services/test",
    contentType: "application/json",
    data: JSON.stringify({category: 42, sort: 3, type: "pdf"}),
    dataType: "json",
    success: function(json, status){
        if (status != "success") {
            log("Error loading data");
            return;
        }
        log("Data loaded!");
    },
    error: function(result, status, err) {
        log("Error loading data");
        return;
    }
});

服务器响应以下标题:

The server responds with the following headers:

Content-Disposition:attachment; filename=export-1282022272283.pdf
Content-Length:5120
Content-Type:application/pdf
Server:Jetty(6.1.11)

另一个想法是生成PDF并将其存储在服务器上,并返回JSON,其中包括一个URL到文件。然后,发出在阿贾克斯成功处理程序再次调用做类似如下:

Another idea is to generate the PDF and store it on the server and return JSON that includes a URL to the file. Then, issue another call in the ajax success handler to do something like the following:

success: function(json,status) {
    window.location.href = json.url;
}

但这样做,这意味着我需要让多个呼叫服务器,我的服务器将需要建立下载文件,将它们存储在某处,然后定期清理存储区。

But doing that means I would need to make more than one call to the server, and my server would need to build downloadable files, store them somewhere, then periodically clean up that storage area.

必须有一种简单的方法来实现此目的。想法?

There must be a simpler way to accomplish this. Ideas?

编辑:审查文档为$阿贾克斯之后,我看到了响应的dataType只能是 XML,HTML,脚本,JSON,JSONP,文字之一,所以我猜是没有办法直接下载文件使用一个Ajax请求,除非我嵌入二进制文件中使用数据URI方案的建议在@VinayC回答(这不是我想做的事)。

After reviewing the docs for $.ajax, I see that the response dataType can only be one of xml, html, script, json, jsonp, text, so I'm guessing there is no way to directly download a file using an ajax request, unless I embed the binary file in using Data URI scheme as suggested in the @VinayC answer (which is not something I want to do).

所以我想我的选择是:

  1. 不使用AJAX,而是提交表单后,并嵌入我的JSON数据到表单中值。很可能需要惹隐藏的内置页框和等。

  1. Not use ajax and instead submit a form post and embed my JSON data into the form values. Would probably need to mess with hidden iframes and such.

不使用AJAX,而是将我的JSON数据转换成一个查询字符串,以建立一个标准的GET请求,并设置window.location.href该URL。可能需要使用的事件。在我的点击处理程序preventDefault(),以确保浏览器从应用程序URL变化。

Not use ajax and instead convert my JSON data into a query string to build a standard GET request and set window.location.href to this URL. May need to use event.preventDefault() in my click handler to keep browser from changing from the application URL.

使用我的其他的想法上面,而是增强了从@naikus答案建议。提交Ajax请求的一些参数,使网络服务的知道这是通过Ajax调用被调用。如果Web服务是从一个Ajax调用调用,只是返回JSON的URL来生成的资源。如果资源被直接调用,然后返回实际的二进制文件。

Use my other idea above, but enhanced with suggestions from the @naikus answer. Submit AJAX request with some parameter that lets web-service know this is being called via an ajax call. If the web service is called from an ajax call, simply return JSON with a URL to the generated resource. If the resource is called directly, then return the actual binary file.

我越去想它,我越喜欢最后的选择。这样我可以得到信息反馈有关请求(时间生成,文件的大小,错误信息等),我可以开始下载前对这些信息采取行动。缺点是额外的文件管理服务器上。

The more I think about it, the more I like the last option. This way I can get information back about the request (time to generate, size of file, error messages, etc.) and I can act on that information before starting the download. The downside is extra file management on the server.

任何其他的方法来做到这一点?任何优点/缺点,这些方法我应该知道的?

Any other ways to accomplish this? Any pros/cons to these methods I should be aware of?

推荐答案

letronje 的的解决方案仅适用于非常简单的网页。 document.body.innerHTML + = 需要身体的HTML文本,追加了iframe HTML,并设置页面的innerHTML该字符串。这将擦除任何事件绑定你的页面有,除其他事项。创建一个元素,并使用的appendChild 代替。

letronje's solution only works for very simple pages. document.body.innerHTML += takes the HTML text of the body, appends the iframe HTML, and sets the innerHTML of the page to that string. This will wipe out any event bindings your page has, amongst other things. Create an element and use appendChild instead.

$.post('/create_binary_file.php', postData, function(retData) {
  var iframe = document.createElement("iframe");
  iframe.setAttribute("src", retData.url);
  iframe.setAttribute("style", "display: none");
  document.body.appendChild(iframe);
}); 

或者使用jQuery

Or using jQuery

$.post('/create_binary_file.php', postData, function(retData) {
  $("body").append("<iframe src='" + retData.url+ "' style='display: none;' ></iframe>");
}); 

这是什么实际执行:执行后,以/create_binary_file.php与变量POSTDATA数据;如果该职位成功完成,添加一个新的iframe的页面的主体。假设是从/create_binary_file.php响应将包括一个值'URL',它是生成的PDF / XLS /等文件可以下载文件的URL。添加iframe来引用该URL将导致浏览器推动用户下载该文件,假设Web服务器有适当的MIME类型配置的页面。

What this actually does: perform a post to /create_binary_file.php with the data in the variable postData; if that post completes successfully, add a new iframe to the body of the page. The assumption is that the response from /create_binary_file.php will include a value 'url', which is the URL that the generated PDF/XLS/etc file can be downloaded from. Adding an iframe to the page that references that URL will result in the browser promoting the user to download the file, assuming that the web server has the appropriate mime type configuration.

这篇关于使用Javascript / jQuery来通过POST下载文件JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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