简体   繁体   中英

Download attribute opens file instead of downloading

I want to test downloading a local file using the <a> tag in HTML. The attached code doesn't seem to download the file, instead, it opens it.

 <p>Interested? Download <a href="download_files/ChannelLogo.png" download>here</a></p>

Your code is correct, however, the download attribute only works when you are viewing the code from a server, due to the same-origin policy of most browsers.

Are you previewing the file by double-clicking the file or directly opening it up in a browser? If the URL while previewing starts with something similar to file://FILEPATH_HERE or /Users/FILEPATH_HERE , you are opening the file rather than serving the file. If so, you should run your code from within a localhost setup to test. That may involve running a server locally, or using an editor extension to spin up a project-based server. Once your URL starts with http:// or https:// the download will work as intended.

Alternatively, you could upload the project somewhere on the web.

It depends on where the file is located and how files are being served.

Either way, whether it is a plain static website with local files or being served by a server, you might need to check the href again to make sure it is correct.

Could be something small like /download_files/ChannelLogo.png instead of download_files/ChannelLogo.png .

Edit after question update: Yes answer by Riley is right: it will only download if you are using a server. You could use a server like Node.js to run and test what you would like to do.

Otherwise you could look into Electron if you would like to work with the filesystem more directly, all depending on what it is you would like to do with your program.

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