views:

51

answers:

5

hello there i am constructing a site where i can upload my own mp3 files. So i have the file uploaded to the server and when i link to it the browser plays the song. Is it possible to make it so when the link is press it downloads the file instead of playing it.

For example www.example.com/music/song.mp3 once clicked it downloads instead of playing.

Maybe this could be done in JavaScript?

Thanks so much.

+1  A: 

The easiest way to force a download would be to set the file's Content-Type header to application/octet-stream. You need to do this on the server side though, e.g. with PHP or similar.

Piskvor
+3  A: 

You can tell the browser what to do with a file by sending the content-disposition header. This would be done server side, wherever you serve up the mp3 files from.

http://www.boutell.com/newfaq/creating/forcedownload.html

Jeriko
+1  A: 

You need to set the correct header for your mp3 files. You can do that in your web server's configuration, or you can make a "download" script that will send the correct header, and the contents of the mp3 file

If you ware using PHP, for instance, you could do something like this (from the PHP manual):

<?php
// We'll be outputting a PDF
header('Content-type: audio/mpeg');

// It will be called file.mp3
header('Content-Disposition: attachment; filename="file.mp3"');

// The PDF source is in original.mp3
readfile('original.mp3');
?>
Jan Hančič
Thanks a lot. This worked perfectly.
Matthew Carter
A: 

A few pointers.

  • File uploads could be done e.g. using PHP. See handling file uploads in the PHP manual but be warned : You're in for a lot of learning if you want to do it properly.

  • To play MP3 files in the browser, the best choice is a stylable Flash/JS based player ike jPlayer.

  • To make MP3 files downloadable, build a server side script that sends the right headers like suggested by @Piskvor and @Jan.

Pekka
A: 

I think the better way, rather than having to code PHP for the download would be as follows.

Assuming your web host uses Apache, in your music directory, create a .htaccess file with the following contents:

<Files *.mp3>
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</Files>

This achieves the same thing as the PHP but will apply to all mp3 files.

Uriah