I have the following code, I want to download files of different mime types. Ie docx, pdf etc. I have defined my download action, then bellow am trying to get the file extension for which i direct it to the correct mimetype. But this doesnot seem to work
def download
@uploadedfile = Uploadedfile.find(params[:id])
send_data(
@uploadedfile.upload_file.path,
:filename => @uploadedfile.name,
# :type => 'application/pdf',
# :type=>"*/*",
# :type=> "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
#:type=> MIME::Types.type_for(@uploadedfile.name).to_s,
#:content_type => %w(application/vnd.openxmlformats-officedocument.wordprocessingml.document application/pdf),
:type=> file_extension,
:stream => true,
:x_sendfile=>true,
:url_based_filename => true
)
flash[:notice] = "The file has been downloaded"
end
def file_extension
@uploadedfile = Uploadedfile.find(params[:id])
# ext = File.extname("#{@uploadedfile.name}")
ext = File.extname(@uploadedfile.name)
if (ext == ".pdf")
content_type = "application/pdf"
elsif (ext == ".doc") || ( ext == ".rtf") || ( ext == ".docx")
content_type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
elsif (ext == ".txt")
content_type = "text/Plain"
elsif (ext == ".rar")
content_type = "Application/x-rar-compressed"
elsif (ext == ".jpeg" || ext==".jpg")
content_type = "image/jpeg"
else
content_type = "Application/octet-stream"
end
content_type
end
but this seems not to work, where am i going wrong? Please help
I solved this problem by making a slight change on the def file_extension
to
def file_extension
up = Uploadedfile.find(params[:id])
ext = File.extname("#{up.upload_file}")
if (ext == ".pdf")
"application/pdf"
elsif (ext == ".doc") || ( ext == ".rtf") || ( ext == ".docx")
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
elsif (ext == ".txt")
"text/Plain"
elsif (ext == ".rar")
"Application/x-rar-compressed"
elsif (ext == ".jpeg" || ext==".jpg")
"image/jpeg"
else
"Application/octet-stream"
end
end
I changed this part to ext = File.extname(@uploadedfile.name)
to ext = File.extname("#{up.upload_file}")
where up = Uploadedfile.find(params[:id])