Reputation: 1701
I added mp3 files to the /public folder and I found a bit issue.
In my view I added the links:
= link_to "Interview 1", "/interview_01.mp3"
When I see the link from the page, everything appears normal until I click on it. The browser hangs on for a minute or more, the tile changes to "undefined" and my Google Chrome freezes.
What's wrong with it? How can I make it so people can just download the file?
Upvotes: 0
Views: 2041
Reputation: 644
When you link to an mp3 file, most modern browsers will attempt to play that file directly in the browser. Your browser is likely freezing because whatever plugin your browser is using to begin playing the file is broken. My guess would be you are running windows and it is attempting to use a quicktime plugin or something along those lines.
If you don't want the browser to play the file and you actually want the file to begin downloading, you need to add a few extra headers to the HTTP response. The most important being:
Content-Disposition: attachment; filename="filenamehere.mp3"
My original answer provides instructions for accomplishing this. If this is not what you were hoping to achieve then you can disregard it.
If you want the file embedded directly into the page with the new HTML5 audio tag, you can follow the advice given in the comment to your question by @Alen.
You should try sending the file from a controller action using the #send_file
controller helper method.
= link_to "Inteview 1", :controller => 'files', :action => 'send_file', :filename => 'interview_01.mp3'
Then
class FilesController
def send_file
file_path = "#{Rails.root}/public/#{params[:filename]}"
send_file file_path, :filename => params[:filename], :disposition => 'attachment'
end
end
Reference Rails Api: http://api.rubyonrails.org/classes/ActionController/DataStreaming.html#method-i-send_file
The send_file
method sets the HTTP headers correctly to tell the browser to download the file instead of attempting to render it.
Upvotes: 5