1

Been struggling with this problem for a while. I am trying to force a file download through javascript and PHP.

If I visit the PHP page directly it works but I want the download to start when on a different page but without success.

The URL to the file depends on a value taken from a SELECT item, however this part works as expected so I am leaving it out of the question.

Javascript

var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", postUrl, true); //postUrl = http://www.example.com/downloadFile.php?url=http://www.example.com/files/test.eps

xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send();

PHP

$url = "http://www.example.com/files/test.eps";
$filesize= strlen(file_get_contents($url));

        header('Content-Description: File Transfer');
        header('Content-Type: application/force-download');
        header('Content-Disposition: attachment; filename='.basename($url));
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . $filesize);
        readfile($url);

I have been testing with both GET and POST (not sure which one would be best, feel free to correct me) but for now I am trying to get the GET to work. Like I said, if I visit "http://www.example.com/downloadFile.php" directly the file is downloaded and if I do console.log(xmlHttp.responseText) the file contents is written to the console, but the file is not downloaded when making the request from the other page.

Any help would be greatly appreciated.

Magnetize
  • 364
  • 1
  • 9
  • 17
  • 1
    A different approach. But will solve your problem. http://stackoverflow.com/questions/3749231/download-file-using-javascript-jquery – Rajan Panneer Selvam Nov 10 '14 at 13:41
  • Thanks, I've seen the iframe trick but thought it was kind of dirty. It appears to work with my eps-file though. Problems downloading images, so I guess I have to do something with the MIME-type or something? – Magnetize Nov 10 '14 at 13:56

1 Answers1

1

Turns out I used the link posted by @Vivasaayi, however I did it with a slight twist. Instead of using an Iframe I used a regular a href. PHP-file is unchanged.

Javascript

var downloadLinkID = 'hiddenDownloadLink', downloadHref = document.getElementById(downloadLinkID);
    if (downloadHref === null) 
    {
        downloadHref = document.createElement('a');
        downloadHref.id = downloadLinkID;
        downloadHref.setAttribute('href', postUrl + params);
        downloadHref.setAttribute('onclick', firefoxDownload(postUrl + params)); // FF/IE must have onclick event to make link clickable
        downloadHref.click();

    }

    function firefoxDownload(url)
    {
        window.location.href = url; //Needed for FF/IE to force download of file

    }
Magnetize
  • 364
  • 1
  • 9
  • 17