views:

50

answers:

2

OK, I've had a good read through the "Related Questions" section and I haven't found this answer.

I'm using an ajax request to force a php download. Things are working fine on the PHP end. Let's say I've got a stream of data called DATA. Now, I want to pop up a "Save as..." dialog.

The browser has received a string of hex values. Now, what do I do with this DATA on the client (javascript) side?

This is the PHP code that I'm using, per the link above:

header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename=$file');
readfile($file);

I've tried

  • window.open(DATA) -> hex stream doesn't exist (of course)
  • submitting a form with the action as DATA -> same problem

BTW, If I echo the file from PHP then use window.open, it works sometimes. But not for txt files or jpgs etc.

I've seen this working on other sites - how are they doing it? Thanks in advance.

A: 

Here's the answer I was looking for:

window.open("downloadPage.php");

...which pops up a box every time. The problem with the ajax request was that the returned file stream was interpreted as XMLHttpRequestObj.reponseText.

The browser apparently interprets this differently and doesn't allow the download. So, it's on to the next problem: send POST data to the download page.

Steve
A: 

you have to use headers of content type for getting that download popup.

like this

header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=$file");
    header("Content-Type: application/zip");
    header("Content-Transfer-Encoding: binary");

based on what file you have use different headers, like xls ,csv, pdf,mp3

http://www.ryboe.com/tutorials/php-headers-force-download

http://php.net/manual/en/function.readfile.php

http://www.w3schools.com/media/media_mimeref.asp

zod