Rails 文件上传下载

上传

View

<%= form_for @salary, :url => { :action => "create" }, :html => { :class => "form-horizontal" }, :multipart => true do |f| %
  
"control-label" %>
"input-xxlarge" %>
</div> <% end %>

Controller

def create
    @salary = Salary.new(salary_params)
    @salary.file = upload_file(params[:salary][:pdf_file]) if params[:salary][:pdf_file] != nil
     ...
end

private

# Fiel Upload
def upload_file(file)
  name = file.original_filename
  # file extname : pdf
  # file size : blow 10 MB
  if !['.pdf'].include?(File.extname(name).downcase)
    flash[:warning] = "PDFのみアップロードできます。"
    return
  elsif file.size > 10.megabyte
  flash[:warning] = "10MBまでアップロードできます。"
    return
  else
    name = params[:salary][:user_id].to_s + '_' + params[:salary][:month].to_s + '_' + name
    File.open("public/uploads/#{name}", 'wb') { |f| f.write(file.read) }
  end
  return name
end

下载

View

<%= link_to @salary.file, users_download_path(:file => @salary.file) if @salary.file != nil %>

Controller

def download
  file_url = "public/uploads/#{params[:file]}"
  send_file file_url
end

Route

namespace :users do
  ...
  get "download", to: "salaries#download", as: "download"
end