
Download a file via AJAX
in Using jQuery • 5 years ago
Hi,
I am starting with ajax and got a problem with a download I would like to make via AJAX.
- $( document ).ready(function() {
- console.log("jQuery Version : " + $.fn.jquery)
- var src = $(this).attr('src');
- $.ajax( 'http://localhost/file-stream/response.php', {
- 'xhrFields' : {
- 'responseType' : 'blob'
- },
- 'dataType' : 'binary'
- })
- .complete(function ( xhr ) {
- console.log(xhr);
- var $a = $( '<a />' ), url = URL.createObjectURL( xhr.response );
- $a.attr({
- 'href' : url,
- 'download' : 'document.pdf'
- })
- .trigger( 'click' );
- URL.revokeObjectURL( url );
- });
- });
- });
I always get errors like this on all browsers (this ones from chrome):
- Uncaught InvalidStateError: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'blob').
The downloaded file is not a part of web servers folder or in any of the vhost's folder. It is in a folder, where the webserver has permissions, but cannot use files as a link!
This is the PHP code I use:
- <?php
- $file_path = '/var/www/docs/document.pdf';
- $file_name = 'document.pdf';
- header("Content-Type: application/force-download");
- header("Content-type: application/pdf");
- header('Content-Description: File Download');
- header('Content-Disposition: attachment; filename=' . $file_name);
- header('Content-Transfer-Encoding: binary');
- header('Expires: 0');
- header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
- header('Pragma: public');
- header('Content-length: ' . filesize($file_path));
- ob_clean();
- flush();
- readfile($file_path);
- ?>
Replies(4)
Leave a comment on jakecigar's reply
@jakecigar::
yeah, thats correct. My code is not working on other domains. But this is just an exemple, cause I couldn't get it running within my CMS.
Your exemple is just downloading a png file. But I need to download doc, pdf, zip, etc.. It should download the file in the download folder.
Leave a comment on n00n46's reply
Leave a comment on jakecigar's reply
I have a working PDF download, in this case it’s from a CORS site. I used the plugin and only had to write a few lines of code
- $(function() {
- $("button").click(function() {
- $.ajax({
- url: "http://cors.jejaju.com/Snickerdoodles.pdf", // my URL
- type: "GET",
- dataType: 'binary',
- success: function(result) {
- var url = URL.createObjectURL(result);
- var $a = $('<a />', {
- 'href': url,
- 'download': 'document.pdf',
- 'text': "click"
- }).hide().appendTo("body")[0].click();
- // URL.revokeObjectURL(url);
- }
- });
- });
- });
Leave a comment on jakecigar's reply
Reply to n00n46's question
{"z47173392":[14737000005993546,14737000005993567],"z2950240":[14737000005994920,14737000005999092,14737000005999144]}


0 thoughts to “Jquery download file response”