ファイルアップロード

ビュー

  • フォーム
[app/views/books/new.fhtml]

<%= start_form_tag({:action => 'create'}, :multipart => true) %>
  <%= render :partial => 'form' %>
  <%= submit_tag "Create" %>
<% end_form_tag %>
[app/views/books/_form.fhtml]

<p><label for="book_picture_url">Picture URL</label><br/>
<%= file_field 'file', 'picture_url'  %></p>

fileオブジェクトの picture_url 要素として送られる.

  • アップロード画像の表示
[app/views/books/list.rhtml]

        <% if book.picture_url != "" then %>
          <p><img src="<%= book.picture_url %>" alt="picture"></p>
        <% end %>        

コントロール

IEからのアップロードファイル名は,c:\XXX\YYYY\ZZZ\filename.jpg のようになって送られてくるので,.original_filename で余計なパス情報をカットする.

[app/controllers/books_controller.rb]

  def create
    @book = Book.new(params[:book])
 
    #upload
    #pathがベタ書きだけど
    if params[:file]['picture_url'] != ""
      @filename = params[:file]['picture_url'].original_filename
      @book.picture_url = "http://localhost:3000/images/" + @filename
      Book.save(params[:file]['picture_url'])
    end
 
    if @book.save
      flash[:notice] = 'Book was successfully created.'
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

モデル

  • public/images は,/RAILS_ROOT/public/images のことでもともとあるみたいです.RAILS_ROOTはappの上の事.
[app/models/book.rb]

class Book < ActiveRecord::Base
  def self.save(file)
    File.open("public/images/#{file.original_filename}", "wb"){ |f| f.write(file.read) }
  end

end