1

Is there a way to 'force' the browser to download a file instead of opening that?

<a href="file.txt">Download this file</a>

I've tried the method via js using the window.open("file.txt", "Download");

but no success.

Thx.

Updating:

I've done a php file as follow;

<html>
<a href='dl.php?bid=3'>

<php>
$sql="select barquivo from bibilioteca where bid=$_GET[bid]";
$row=mysql_fetch_assoc(mysql_query($sql));
header("Content-Disposition: attachment;filename=biblioteca/$row[barquivo]");

And it download a file "biblioteca_" with 0 bytes.

Paulo Bueno
  • 2,499
  • 6
  • 42
  • 68
  • The best answer is on this link http://stackoverflow.com/questions/1597732/php-force-file-download-and-ie-yet-again/1597946#1597946 – Paulo Bueno Dec 10 '09 at 19:30

5 Answers5

4

You should do this server-side.

If you send a

Content-type: application/octet

or

Content-disposition: attachment; filename=file.txt

header then the user will be prompted to download.

Greg
  • 316,276
  • 54
  • 369
  • 333
  • 1
    `octet-stream`, usually. However just `octet` would work too simply due to being an unknown type. – bobince Dec 10 '09 at 17:23
2

Not at the javascript level. You can have a good deal of control on what the user agent (browser) will attempt to do, by changing the the Mime Type of the content served - that can be done from the web server or server side application.

That means, your ".txt" file is sent to the browser with a

Content-Type: text/plain 

http header. If instead it is served with:

Content-Type: application/octect-stream 

http header instead, most likely the user will be prompted to save the file (regardless of the file name or extension)

jsbueno
  • 99,910
  • 10
  • 151
  • 209
1

Can't be done in pure Javascript as far as I know. You have to send the appropriate headers server side.

If you can use Apache´s .htaccess settings (much easier) or PHP (more complicated because you'd have to parse txt files through PHP, or introduce a PHP script to pass through the files), you can refer to the accepted answer given here.

Community
  • 1
  • 1
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
1

It's up to the server to send the appropriate header.

Content-Disposition: attachment;filename=schmoo.mp3
Jonathan Feinberg
  • 44,698
  • 7
  • 80
  • 103
1

For those looking to d/l files trhough a link heres the best solution

PHP: Force file download and IE, yet again

by cballou

Community
  • 1
  • 1
Paulo Bueno
  • 2,499
  • 6
  • 42
  • 68