Friday, June 20, 2008

responds to mp3



To allow a client to download an MP3 file from Rails:

First, download the mime-types gem:


gem install mime-types


Then, register mp3 as a Mime type in environment.rb:


Mime::Type.register 'audio/mpeg', :mp3


Then in your "respond_to" block, add a handler for mp3 files. Redirect the user to the location of the file you want to download.


def show_recording_audio_file
@recording = Recording.find(params[:id])
@audio_file = @recording.audio_file
respond_to do |format|
format.html # index.html.erb
format.mp3 {
redirect_to @audio_file.public_filename
}
format.xml { render :xml => @audio_file }
end
end


You could also send the file directly:


send_file RAILS_ROOT + "/public" @audio_file.public_filename + ".mp3"