Paulo Bueno
Paulo Bueno

Reputation: 2569

Javascript JQuery link to download a txt file

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.

Upvotes: 1

Views: 7416

Answers (5)

Paulo Bueno
Paulo Bueno

Reputation: 2569

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

PHP: Force file download and IE, yet again

by cballou

Upvotes: 1

jsbueno
jsbueno

Reputation: 110666

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)

Upvotes: 2

Jonathan Feinberg
Jonathan Feinberg

Reputation: 45364

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

Content-Disposition: attachment;filename=schmoo.mp3

Upvotes: 1

Greg
Greg

Reputation: 321806

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.

Upvotes: 4

Pekka
Pekka

Reputation: 449783

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.

Upvotes: 1

Related Questions