POST to server, receive PDF, deliver to w / jQuery user

I have a link that the user clicks to get a PDF file. In jQuery, I create an ajax POST call for the server to get a PDF file. PDF comes up to me with the right content headers, etc., which usually force the browser to open the Reader plugin or allow the user to save the PDF file.

Since I get a PDF with ajax call, I'm not sure what to do with the data that I get in the OnSuccess callback. How can I provide the data that I receive in the browser and let it perform its default task with a PDF response?

+46
jquery post ajax pdf
Feb 02 '10 at 18:26
source share
7 answers

You don't need jQuery at all. Just submit your POST via the form, as a rule, and on the server side add an HTTP header

Content-Disposition: attachment; filename="whatever.pdf" 

The browser will complete its task by default.

Alternatively, if you want to be more attentive to reporting any errors that may occur during PDF generation, you can do this. Send your parameters to your server using jQuery. On the server, generate binary content and cache it somewhere for several minutes, accessible with the key that you put in the user session, and return the "Ajax" response to your page (or if an error occurs, return the "error" answer). If the page returns a success response, it can immediately do something like:

 window.location = "/get/my/pdf"; 

The server then returns the contents of the cached PDF file. Be sure to include the Content-Disposition header as above.

+31
Feb 02 '10 at 18:40
source share

Take a look at the jQuery Plugin to request download of Ajax files

The entire plugin is only about 30 lines of code (including comments).

The call is pretty similar to a jquery ajax call.

 $.download('/export.php','filename=myPDF&format=pdf&content=' + pdfData ); 

Of course, you must set the content and Content-Disposition headers on the server side, as with any such download.

In java, I would do something like this

 response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "attachment; filename="exported.pdf"); 
+50
Feb 02 2018-10-18T00-02-02
source share

The answer, which mentions โ€œa jQuery plugin for querying Ajax files,โ€ made me move in the right direction, but it didnโ€™t work completely for my situation, since I have a complex object and an array of objects, search criteria / filter data. I decided that I would share my code if someone else came across this situation.

 $.download = function (url, data, method) { if (url && data) { //convert the data object into input HTML fields var inputs = ''; var convertToInput = function (key, keyStr, obj) { if (typeof obj === 'undefined') { return; } else if (typeof obj === "object") { for (var innerKey in obj) { if (obj.hasOwnProperty(innerKey)) { var innerKeyStr = ''; if (keyStr === '') { innerKeyStr = innerKey.toString(); } else { innerKeyStr = keyStr + "[" + innerKey.toString() + "]"; } convertToInput(innerKey, innerKeyStr, obj[innerKey]); } } return; } else if ($.isArray(obj)) { obj.forEach(function (item) { convertToInput(key, keyStr + "[]", item); }); return; } inputs += "<input type='hidden' name='" + keyStr + "' value='" + obj + "' />"; }; convertToInput(null, '', data); //send request jQuery('<form action="' + url + '" method="' + (method || 'post') + '">' + inputs + '</form>').appendTo('body').submit().remove(); }; }; $.download('/api/search?format=csv', searchData, 'POST'); 

This probably doesn't matter much, but to provide some context, I have a javascript and knockout user interface that gets called in WebAPI, MVC4, and nHibernate. The `format = csv 'part of the query string starts MediaTypeFormatter to convert the returned models to a CSV file type. If I leave this, I will return the models back from the API and be able to populate the Slick grid for display.

+3
Feb 05 '13 at 21:51
source share

I had the same problem, but at the top, use the RESTFUL webservice for this and I have a complex data object that I have to publish.

My solution: as a jQuery plugin, I create a temp form and submit it. But I am sending a data object as a parameter with json content (I am using AngularJS here, but it should also work with jQuery.param() .)

JavaScript:

 $('<form target="_blank" action="' + appConstants.restbaseurl + '/print/pdf" method="POST">' + "<input name='data' value='" + angular.toJson($scope.versicherung) + "' />" + '</form>').appendTo('body').submit().remove(); 

on the server side we use the CXF REST Service with the JACKSON Provider:

Spring Configuration:

 <jaxrs:server id="masterdataService" address="/"> <jaxrs:serviceBeans> <ref bean="printRestServiceBean" /> </jaxrs:serviceBeans> <jaxrs:providers> <bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" /> <bean class="de.controller.ExceptionHandler" /> </jaxrs:providers> </jaxrs:server> 

in the controller, I extracted the parameter and converted it back to Java Pojo:

 package de.controller; import javax.ws.rs.Consumes; import javax.ws.rs.FormParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.codehaus.jackson.map.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; @Path(Constants.PRINT_PATH) @Consumes({ MediaType.APPLICATION_JSON, "application/x-www-form-urlencoded"}) @Produces("application/pdf; charset=UTF-8") public class PrintRestController { @Autowired private PrintService printService; @POST @Produces("application/pdf") @Path("/pdf") public Response getPDF(@FormParam("data") String data) { return printService.getPDF(json2Versicherung(data)); } private Versicherung json2Versicherung(String data) { Versicherung lVersicherung = null; try { ObjectMapper mapper = new ObjectMapper(); lVersicherung = mapper.readValue(data, Versicherung.class); } catch(Exception e) { LOGGER.error("PrintRestController.json2Versicherung() error", e); } return lVersicherung; } } 

in PrintService I create a pdf file and answer:

 @Override public Response getPDF(Versicherung pVersicherung) { byte[] result = ... //build the pdf from what ever ResponseBuilder response = Response.ok((Object) result); response.header("Content-Disposition", "inline; filename=mypdf.pdf"); return response.build(); } 

This solution works for all browsers (even for IE9 that cannot handle data URLs), and on tablets and smartphones, and it has no problems with popupblockers

+2
Sep 17 '14 at 12:22
source share

A jQuery plugin for requesting Ajax files Uploading files is essentially creating a form, adding message data as hidden fields, adding it to the body of the page, sending and deleting it.

In my case, I did not have a form, and only a piece of data should be placed as is. This was done for the next solution. On the server side, I can get the data simply by reading the "data" parameter from the request and URI decoding.

 function postAndDownload(url, data) { encodedData = encodeURIComponent(data); $("<form>") .attr("action", url) .attr("method", "post") .append( $("input") .attr("type", "hidden") .attr("name", "data") .attr("value", encodedData) ) .appendTo("body") .submit() .remove(); }; 
+1
Jun 22 '15 at 16:13
source share

I donโ€™t understand why you need ajax request for the url to download the file! But if it looks more like the client itself, it creates some content to download - use the uri data. Works great for Chrome and Firefox 20+. Safari and IE NOT! If Flash is enabled, you can use the bootloader.

Ah, after reading your code, I see you want to send a bunch of parameters. Well, if the query string is too long (IE8- has a limit of 2083), why not just use the anchor with the correct URL?

  $('a.export-csv').click( function (evt){ linkEl.attr('href','/export?' + encodeURIComponent(formQueryString())); return true; }); 

The above allows you to change the URL to the default event (click).

0
May 08 '13 at 3:01
source share

I think itโ€™s best to create a temp pdf file in the download folder and then upload the file using the pop-up window with iframe .. Chrome will download it instantly, but I suggest that for other options Acrobat Reader should be installed on view pdf. but again you can use flashpaper too :)

-one
Apr 25 2018-12-12T00:
source share