开发者

Can you use AJAX to echo out a file for download?

开发者 https://www.devze.com 2023-01-06 13:41 出处:网络
I wanted to let a user download a file by simply clicking a button. Thing is, the file doesn\'t actually exist - its just some dynamic content.

I wanted to let a user download a file by simply clicking a button. Thing is, the file doesn't actually exist - its just some dynamic content.

So lets say:

$('a.download').click(function(){

$.post('get.php');
})

and in my PHP:

header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; fi开发者_JS百科lename=something.txt");
header("Content-Type: text");
header("Content-Transfer-Encoding: binary");
echo 'abcbdefg'

Is that valid? Is there some other way to do it?


Just create a link to the file, like this:

<a href="get.php">download my file</a>

Whenever there's a request for a file of type PHP, your webserver will first process the file and output whatever text it contains to the client; you don't have to do anything special just because it's dynamic.

Using $.post() doesn't make sense for what you want to do; that POSTs data to the url you specify, it doesn't prompt the user to save a file.


Yeah, that's valid. I'm pretty that's the best way to do it.

0

精彩评论

暂无评论...
验证码 换一张
取 消