简体   繁体   中英

Downloading a music file instead of playing it in the browser

I'm trying to make a downloader on my website which starts downloading the selected files but the problem is it is a music file which just opens up in a new window and starts playing it.

The script is (don't worry about the id part it is for the next part):

function downloadsong(id){
    var url = ("/music/downloadablesongs/linkin-park/Minutes-to-Midnight/wake.mp3");
    window.open(url,'Download')
}

If you can configure the server that hosts the files, you should be able to manipulate the HTTP headers to include a "Content-Disposition" header. This will prompt the user agent (browser) to save the file, rather than allow it to automatically detect/interpret the content.

The basic format is:

Content-Disposition: attachment; filename=$file_name.ext 

It depends on the user's browser. Usually, plugins or built-in browser capabilities take over and play it instead of letting the browser download.

What you can do is to have the file carry no extension (ie. remove .mp3 ). That way, it won't be picked-up by plugins. The down side is additional work for the user, by having to add the extension manually.

Other way is simply use the download attribute. I think is the simplest way.

<a href="/music/downloadablesongs/linkin-park/Minutes-to-Midnight/wake.mp3" download>

See more here .

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