/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] Force download of MP3 file instead of streaming

Hi, i had encountered problem with MP3 file links:
in IE/Safari/Chrome, when a link to a MP3 file is clicked, the download starts correctly; but in Firefox that doesn’t happen – clicking the MP3 file link, it starts an unwanted streaming through a preinstalled FF media plugin.
I need to [B]force MP3 file download[/B] in all browsers, is there a simple way to do that in Javascript?

to post a comment

30 Comments(s)

Copy linkTweet thisAlerts:
@scragarMar 24.2011 — Not really in javascript, but if you set the files mimetype to [b]application/octet-stream[/b] you would normally receive the dialog(since that's a universal binary/cannot display in the browser but not saying what file type it is yet mime)
Copy linkTweet thisAlerts:
@MrSnowDropauthorMar 24.2011 — Not really in javascript, but if you set the files mimetype to [b]application/octet-stream[/b] you would normally receive the dialog(since that's a universal binary/cannot display in the browser but not saying what file type it is yet mime)[/QUOTE]

I'm using HTML/VBscript/Javascript (not PHP) in my webpages, but i thought to open a Multimedia Thread because the problem is an unwanted streaming process.

:o

So, how is it possible to change a MIME attribute of an MP3 file?... The need is to leave the file with his original extension because the same file is managed by a web-mediaplayer, but i'd like to let a download by clicking a specified button.
Copy linkTweet thisAlerts:
@Eye_for_VideoMar 24.2011 — Another option is to use a small PHP file to handle the download, put in the same folder as the .mp3:
[CODE]<?php
$file = $_GET['file'];
header ("Content-type: octet/stream");
header ("Content-disposition: attachment; filename=".$file.";");
header("Content-Length: ".filesize($file));
readfile($file);
exit;
?>[/CODE]

which can be accessed in any anchor like this:
[CODE]<a href="direct_download.php?file=fineline.mp3">Download the mp3</a>[/CODE]
see sample page here:

http://www.cidigitalmedia.com/tutorials/direct_download/direct_download.html

Best of luck,

Eye for Video

www.cidigitalmedia.com
Copy linkTweet thisAlerts:
@MrSnowDropauthorMar 25.2011 — Thanks EyeForVideo, it seems PHP is the only way to resolve the problem... Unfortunately my pages are ASP extensions and dialog with my Database through VBscript code, so PHP is a little uncomfortable; that's the reason why i hope in a kind of Javascript solution ?

I've to learn PHP and create a dynamic page which redirects to MP3 files ([I]download.php?fileID=1[/I])... At the moment, i have to admit it, have really no idea in how to build dynamic php code.

Thanks again, regards.
Copy linkTweet thisAlerts:
@Eye_for_VideoMar 25.2011 — Are you sure that it has to be that complex?

You might want to at least give it a try.

Just create a simple PHP file from the code above. Name it

direct_download.php

It is NOT a part of any Web page, it is a small separate file, it just needs to reside in the same folder as the mp3.

The <a> just needs to use that file as the href.

It's just a plain anchor... nothing special, no different than linking to any other web page or file.

Best of luck,

Eye for Video
Copy linkTweet thisAlerts:
@scragarMar 25.2011 — It's possible in asp.

&lt;%
Response.ContentType = "Application/octet-stream";
string FilePath = MapPath("song.mp3");
Response.WriteFile(FilePath)
Response.End()
%&gt;
Copy linkTweet thisAlerts:
@MrSnowDropauthorMar 25.2011 — @EyeForVideo - Sure, i'll give a try next days... the other thing to consider, is that there's not a single file, but i have to manage a lot of MP3 through a Database, so i have to make the php-content dynamic: the php page has to request an ID number, corresponding to a MP3 file in the DB... i'll study some php to do that (i think is a little different from asp/vbscript code).

Regards
Copy linkTweet thisAlerts:
@scragarMar 25.2011 — I've just had another thought, can't you just modify the iis settings?

http://technet.microsoft.com/en-us/library/bb742440.aspx
Copy linkTweet thisAlerts:
@MrSnowDropauthorMar 25.2011 — It's possible in asp.

&lt;%
Response.ContentType = "Application/octet-stream"
string FilePath = MapPath("song.mp3")
Response.WriteFile(FilePath)
Response.End()
%&gt;
[/QUOTE]


I'll try again, but at the moment this is the result:

Microsoft VBScript runtime error '800a000d'

Type mismatch: 'mappath'

?
Copy linkTweet thisAlerts:
@MrSnowDropauthorMar 25.2011 — I've just had another thought, can't you just modify the iis settings?

http://technet.microsoft.com/en-us/library/bb742440.aspx[/QUOTE]


I think that could be a possible solution, although now the result is:

in IE - nothings changed (but it's ok, with IE i had no problems in download <a href="song.mp3">...)

in FF - it asks me if i want to save the whole ASP page!!! ?

I'll have to study hard next days, thanks a lot for the moment ?
Copy linkTweet thisAlerts:
@Eye_for_VideoMar 26.2011 — the PHP part is just one simple file and can handle multiple files... here's an example:

http://www.worldbarefootcenter.com/video/download_video.html

Download links for a gazzillion video.

It's just an anchor... if you can create a dynamic anchor (forget about there being a link to the PHP file).. link to it just as if it where an image file.

Best wishes,

EfV
Copy linkTweet thisAlerts:
@MrSnowDropauthorMar 26.2011 — the PHP part is just one simple file and can handle multiple files... [/QUOTE]

WONDERFUL, PHP mini-page works pefect!... I'm sorry, i didn't immediately understood that it meant to be a dynamic page, i thought "file" was only an example in php... :o

I only have to put it in any folder where MP3 files are placed (the files are album-ordered), but really this is not a problem because the php code is very short.

Well, finally i have to admit that PHP code has so many rich functions and i don't understand why other server-side languages (like ASP) cannot do the same things...

Thanks a lot EyeForVideo!
Copy linkTweet thisAlerts:
@DominikHoffmannFeb 09.2012 — Another option is to use a small PHP file to handle the download, put in the same folder as the .mp3:
[CODE]<?php
$file = $_GET['file'];
header ("Content-type: octet/stream");
header ("Content-disposition: attachment; filename=".$file.";");
header("Content-Length: ".filesize($file));
readfile($file);
exit;
?>[/CODE]

which can be accessed in any anchor like this:
[CODE]<a href="direct_download.php?file=fineline.mp3">Download the mp3</a>[/CODE]
see sample page here:

http://www.cidigitalmedia.com/tutorials/direct_download/direct_download.html

Best of luck,

Eye for Video

www.cidigitalmedia.com[/QUOTE]

Unfortunately, using Safari, when I follow the download link using your PHP code, Safari downloads the PHP code, not the referenced MP3 file.

Will this not work, if the page code is in a directory one level higher than the MP3 files and the PHP code?

Yours,

Dominik Hoffmann
Copy linkTweet thisAlerts:
@Eye_for_VideoFeb 09.2012 — Are you saying that the download links I posted do not work in Safari?

The links all work just fine in Safari on my machine.

Or are you having problems when you implement that download php file?
[CODE]<a href="direct_download.php?file=fineline.mp3">Download the mp3</a>[/CODE]
of course the href=" has to be the correct path. So if the web page with the link on it is one level up or down, the path has to reflect that.... but it will work just fine.

Also the file= name has to be changed to the name of the file you are downloading. If you put file=direct_download.php, then it will download that file. So recheck your link code.

EfV
Copy linkTweet thisAlerts:
@DominikHoffmannFeb 10.2012 — Are you saying that the download links I posted do not work in Safari?

The links all work just fine in Safari on my machine.

Or are you having problems when you implement that download php file?
[/QUOTE]

My issue was that I didn't understand that the PHP code snippet is for server-side execution. I was trying to use it while hosting content on my Apple MobileMe iDisk.

Thanks everyone for your help!
Copy linkTweet thisAlerts:
@bigblackpapaJan 02.2013 — Please, do not create a public file proxy on your server, as suggested by "Eye for Video" and "scragar", this is a MEGA HUGE security hole :eek:, an EXTREMELY DANGEROUS feature :eek:! Anyone could use it to download anything from the server, including password files, personal cookies, credit card information, stealing identity and even locally crack all username / passwords to remotely access your server and use it for whatever they want... NEVER CREATE A PUBLIC FILE PROXY :mad:!!! Geez...
Copy linkTweet thisAlerts:
@jackoconnellJan 17.2013 — Just a quick thought: any zip file is downloadable. Just place your mp3 in it.

Jack O'Connell
Copy linkTweet thisAlerts:
@TimothyJMcGowanMar 28.2013 — Thank you, all who contributed to this. You've just made things a lot easier for me. Some of my clients didn't know how to right-click a file and what to choose to save the file to their computer. Even with the instructions right there on the page, it was too difficult. Now when they click on a link, their browser asks whether they want to run or save the file. Excellent!

I did make one modification: I put direct_download.php in a dedicated folder and link to it that way: <a href="[my catch-all folder]direct_download.php?file=..."> That way, I don't have to remember to copy the php file to every folder in which I'm storing files for download, and I can still use it on any page on the site.

I need to make my site more accessible, especially to mobile users, and more standards-compliant, so I'll be studying here when I have the time.

-- Timothy J. McGowan
Copy linkTweet thisAlerts:
@samiaegApr 19.2013 — I'm using HTML/VBscript/Javascript (not PHP) in my webpages, but i thought to open a Multimedia Thread because the problem is an unwanted streaming process.

:o

So, how is it possible to change a MIME attribute of an MP3 file?... The need is to leave the file with his original extension because the same file is managed by a web-mediaplayer, but i'd like to let a download by clicking a specified button.[/QUOTE]


yes , i'm wondering too
Copy linkTweet thisAlerts:
@diveshlalitApr 22.2013 — <?php

//Force file download instead of streaming

//Coded by Code018


$file=$_GET['file'];

$file=str_replace(" ","%20",$file);

header('Content-type: application/octet-stream');

// It will be called the base file name

$url = $file;

$file_name = basename($url);

//lets be nice to the user and replace the spaces with happy things

//$file_name=str_replace("%20","_",$file_name);

//this is the filename we get to play with

$infile = $url;

$file_name = stristr ($infile,basename ($infile));

header('Content-Disposition: attachment; filename="'.urldecode($song_name[COLOR="#FF0000"].mp3[/COLOR].'"');

// The File source is in .mp3 originally

//This is the file that we are downloading

readfile(stripslashes($file));


?>

when add .mp3 file download but not actual[/QUOTE]

pls reply fast
Copy linkTweet thisAlerts:
@PexxMay 23.2013 — Here's how you make download link for MP3 files.

change "octet/stream" to "audio/mp3"
Copy linkTweet thisAlerts:
@AfsanaJasiSep 15.2013 — Another option is to use a small PHP file to handle the download, put in the same folder as the .mp3:
[CODE]<?php
$file = $_GET['file'];

echo"$file";

header ("Content-type: octet/stream");
header ("Content-disposition: attachment; filename=".$file.";");
header("Content-Length: ".filesize($file));
readfile($file);
exit;
?>[/CODE]

which can be accessed in any anchor like this:
[CODE]<a href="direct_download.php?file=fineline.mp3">Download the mp3</a>[/CODE]
see sample page here:

http://www.cidigitalmedia.com/tutorials/direct_download/direct_download.html

Best of luck,

Eye for Video

www.cidigitalmedia.com[/QUOTE]




when I use it in my website and browse from my iPhone then a unknown result is shown such as " •ÄÔäô¥µÅÕåõVfv†–¦¶ÆÖæö7GWgw‡—§·Ç×ç÷5!1AQaq"2‘¡±B#ÁRÑð3$bár‚’CScs4ñ%¢²ƒ&5ÂÒD“T£dEU6teâò³„ÃÓuãóF”¤…´•ÄÔäô¥µÅÕåõVfv†–¦¶ÆÖæö'7GWgw‡—§·ÇÿÚ?½Ò:{ÆéØ.†ž”Â8Tº¦ß€]·ãaa]™’vããVëmwƒX7½4 4HlNÝÆnoö›íOЉôÛ¯¥õú·Ûõ?9ÌîÇ4dmæ[Uµ¾ßókÜô€Ñ h®±Ó:w@ÿ9½9õ°UF«yCòÐÆ_¯øGæ9–-®‰}¹¦äK*»‹,qÔ—:¶9äÿiyÇøÅúÒ&gt;²u_ª} ã"§ÞÁuì2Ë-'eUÖæû]E½KlÿIÿ½:ŠÛ‰V-.&gt;ž;S&gt;hÿ©Nˆ²˜‹+¼ÿ¬*×8x¸£¾û*µ™W‰‹>jeÔ5.p×C÷îTnw‘ÿ4ÿr½nnPâ÷šÁë?]qz&gt;Cq³³r{뵕·pØé÷ûu6Ei,®pð?æ»û•+œßþk¿ò*•ŸãC˜¦ìûhù$'ÿŒn¦æ¹ÔQÔ’]´wÔïjˆÆdÜöùÿšïüŠ£sëñ?æ»ÿ"·*ë½m„Ô-øû|'÷[&gt;±ýau‡ÉŸúM0ÒÒò¹îqu'z–¸ì2744ï‘ôÜß ¨]e¬X×CH‡!ÃéVÿÝ{WEÕúÇ]Îv#lê6z˜÷ŒkY춶Žö1¾**Y¾²Ó™~Ks_›”Æ}µÍeE¶šÿG{?G³ù¿Ñû?ëŠ2U„–¹õI‡ÅVÜÍÓ+¯»ë¿×Ìu[~uÓÿ¤•õÏëQ½¶¢òöðïN¯ø´Ae„ieÿÑèú$ì`“ÉŒ_¯ÒË~¯ôkAi¾£”ÝC¿5øt;ýýȳü/óÍ«X¾²YÐúû çgn¦‹ŽêØë³þÞÚªø5OüýG®ßG®uŠ}F½ÁÝ? Ã逦^Ïô?÷Ÿá¿œþcùÇo@/&èßøªú¦ìf¬ÙÀÚÇ3§VH$4û.Ëwî{wSOýwþ z+îhó§Õÿ¬ýC§egáÐìn¥–ÜvØá´ÓcþÓS«sf½›*±‹£îsm/*õXÝõYXk˜æž]Ü×µ>^+ @*ËÛûÁV²Ù˜ü?ÁÎ¥”4äGýõT³;0ó‘gÈÇäN$¤’ÅìÈѦ×OƒýʏìË/ÍʵØ"ë[è׺ÊZ÷46½Û*Æþ“r=¹y×Ú¶ïïY*¿uٲ繦ymUùÿ)0•¤·Ó:£GèñCÈVÁùZ³z¶WgNÌ{Û´>w__qGÔÜ“ÝQä}úª™í«ìwC«@ç9*L;-;&·¦äϺì*â>ž]C·òw*¶tæCS¦Ô%ÎvCœÔ©G*–1îs6ɘE•ÕqN^) Z)÷˾‹¶þeŸÉL+ ÍwIË˪ªº¾8,6—¼Ó‘´43.........." like this.

please help me
Copy linkTweet thisAlerts:
@sanaroseSep 30.2013 — All articles is amazing and very information's accounting to me.
Copy linkTweet thisAlerts:
@CurrentWaveJan 10.2014 — Please, do not create a public file proxy on your server, as suggested by "Eye for Video" and "scragar", this is a MEGA HUGE security hole :eek:, an EXTREMELY DANGEROUS feature :eek:! Anyone could use it to download anything from the server, including password files, personal cookies, credit card information, stealing identity and even locally crack all username / passwords to remotely access your server and use it for whatever they want... NEVER CREATE A PUBLIC FILE PROXY :mad:!!! Geez...[/QUOTE]

Are you saying that the PHP script creates a security risk? How about changing the default Http headers?

I am in the same boat, and tried just changing my the files metadata type to application/octet-stream but that still played the mp3. When I change it to something like application/msword it forces download and/or offers to open it in MS-Word - yikes! So I tried octet/stream, which is wrong I know but it forced download.....however I worry about people using iTunes and such, will messing with the Content-Type mess up other things?

I'm sorry I'm not following - can someone straighten me out?

Thanks
Copy linkTweet thisAlerts:
@CurrentWaveJan 10.2014 — I worry about people using iTunes and such, will messing with the Content-Type mess up other things? [/QUOTE]

After much testing I've found this to be true.

Hi, i had encountered problem with MP3 file links:

in IE/Safari/Chrome, when a link to a MP3 file is clicked, the download starts correctly; but in Firefox that doesn't happen - clicking the MP3 file link, it starts an unwanted streaming through a preinstalled FF media plugin.

I need to [B]force MP3 file download[/B] in all browsers, is there a simple way to do that in Javascript?[/QUOTE]


No not with Javascript, as others have said, but by using http headers and Content-Disposition one can tell all browsers that the mp3 is an attachment there by forcing the 'Save' window. Leave the Content-Type set to audio/mepg, so iTunes, etc. recognize the file.

See these other forum posts for details -

http://www.webdeveloper.com/forum/showthread.php?133284-prompt-for-save-or-open-a-pdf-or-doc-file&p=691616#post691616

http://www.webdeveloper.com/forum/showthread.php?107318-How-do-I-force-an-open-save-dialogue-on-a-download&p=572200#post572200

For older browsers make sure Content-Type appears before Content-Disposition - see this article: http://www.jtricks.com/bits/content_disposition.html
Copy linkTweet thisAlerts:
@monkseeApr 11.2014 — Hi Eye for Video. Thanks for this solution which i just found on the net. I want people to download music from my site. This works on my desktop but I got someone to test it on their mobile and it just downloads the php file. Do you know is it suppose to work on mobile? Thanks a lot ?

Sarah
Copy linkTweet thisAlerts:
@web_proApr 12.2014 — Another option is to use a small PHP file to handle the download, put in the same folder as the .mp3:
[CODE]<?php
$file = $_GET['file'];
header ("Content-type: octet/stream");
header ("Content-disposition: attachment; filename=".$file.";");
header("Content-Length: ".filesize($file));
readfile($file);
exit;
?>[/CODE]

which can be accessed in any anchor like this:
[CODE]<a href="direct_download.php?file=fineline.mp3">Download the mp3</a>[/CODE]
see sample page here:

http://www.cidigitalmedia.com/tutorials/direct_download/direct_download.html

Best of luck,

Eye for Video

www.cidigitalmedia.com[/QUOTE]


Hi,

I tried the above but when I call the .mp3 file I receive the following error message:

Error 500: (Internal server error)

Any thoughts?
Copy linkTweet thisAlerts:
@johnnya23Jun 26.2015 — I'm trying to implement this in wordpress while hosting the audio on amazon s3

upload the file direct_download.php containing
[code=php]
<?php
$file = $_GET['file'];
header ("Content-type: octet/stream");
header ("Content-disposition: attachment; filename=".$file.";");
header("Content-Length: ".filesize($file));
readfile($file);
exit;
?>
[/code]

to the same folder as the audio then:

<a href="https://s3-us-west-2.amazonaws.com/my-bucket/direct_download.php?file=SoonerOrLater.mp3">Download the mp3</a>

clicking on the link downloads the php file.
Copy linkTweet thisAlerts:
@choibaiJul 22.2015 — It is NOT a part of any Web page, it is a small separate file, it just needs to reside in the same folder as the mp3. The <a> just needs to use that file as the href.
Copy linkTweet thisAlerts:
@fatima21Jul 27.2015 — Unfortunately my pages are ASP extensions and dialog with my Database through VBscript code, so PHP is a little uncomfortable; that's the reason why i hope in a kind of Javascript solution
×

Success!

Help @MrSnowDrop spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.5,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...