1

I am using ajax to called download.php page , but it is not working .What could the problem in below code .

AJAX::

 $.ajax({
  type: "POST",
  url: 'downloadsample.php',
  data: {
  imagepath: "../ReportCard/imagepost.png"
  },
   success:function(data)   { 
    alert('sample download done ');
    }

    });

PHP Code ::

<?php

if ( isset($_POST["imagepath"]) && !empty($_POST["imagepath"]) ) { 
$file = $_POST['imagepath'];

    // Fetch the file info.
    if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    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));
    ob_clean();
    flush();
    readfile($file);
    exit;
    }
    else {
        die('The provided file path is not valid.');
    }

}
    ?>
anam
  • 3,905
  • 16
  • 45
  • 85

2 Answers2

1

you can't download file directly by ajax. you can redirect the user to your download page or you can try with iframe. i mean use hidden iframe or generate iframe dynamically what ever you like and put source of this iframe to your download URL.

user3011768
  • 191
  • 2
  • 3
  • 11
0

you can't do it through Ajax because JavaScript cannot save files directly to a user's computer (out of security concerns). Unfortunately pointing the main window's URL at your file download means you have little control over what the user experience is when a file download occurs.

Try jQuery File Download which allows for an "Ajax like" experience with file downloads complete with OnSuccess and OnFailure callbacks to provide for a better user experience. Take a look at blog post on the common problem that the plugin solves and some ways to use it and also a demo of jQuery File Download in action. Here is the source

Here is a simple use case demo using the plugin source with promises. The demo page includes many other, 'better UX' examples as well.

 $.fileDownload('some/file.pdf')
    .done(function () { alert('File download a success!'); })
    .fail(function () { alert('File download failed!'); });
Adil Abbasi
  • 3,161
  • 1
  • 40
  • 35