简体   繁体   中英

How to download a text file onclick using javascript or HTML

I just want to download a .txt on click it. i am using the below html code:

<a href="d:/file.txt">Download</a>

this code is working for .docx files not for .txt file.

Text files are displayed in the browser when the content-type is sent as text. You should Try to send it with a different content-type or use a language such as PHP to send it as a download.

please try

<a href="d:/file.txt" download="my_text_file">Download</a>

The download="my_text_file" attribute indicates that the target will be downloaded when clicked on the link.. and my_text_file will be new name for that file...

You need to specify the file: protocol. Otherwise, the browser thinks that d: is a protocol name. You also need the download attribute to make it download the file instead of displaying it in the browser.

So it should be:

<a href="file:///d:/file.txt" download>Download</a>

But this seems pointless. The file d:/file.txt is already on your computer, why do you need to download it? Normally you download a file from the server to the client.

To expand on the answer from @barmar:

Taking the jquery question tag into consideration, check out Download File Using jQuery . Here's the code example from that post:

$('a').click(function(e) {
    e.preventDefault();  //stop the browser from following
    window.location.href = 'uploads/file.doc';
});

<a href="no-script.html">Download now!</a>

You can change the value assigned to window.location.href to the file you would like to download.

Try this:

<a href="d:/file.txt" download>Download</a>

It is working for me.

Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM