`

Rails2.2.2之文件上传下载

 
阅读更多
1. 创建一个保存文件的表,然后rake db:migrate同步到数据库
class CreatePictures < ActiveRecord::Migration
  def self.up
    create_table :pictures do |t|
      t.string :comment
      t.string :name
      t.string :content_type
      # If using MySQL, blobs default to 64k, so we have to give
      # an explicit size to extend them
      t.binary :data, :limit => 1.megabyte
    end
  end

  def self.down
    drop_table :pictures
  end
end


2. 创建UploadController
class UploadController < ApplicationController
  def get
    @picture = Picture.new
  end

  def save
    @picture = Picture.new(params[:picture])
    if @picture.save
      redirect_to(:action => 'show', :id => @picture.id)
    else
      render(:action => :get)
    end
  end

  def show
    @picture = Picture.find(params[:id])
  end

  def picture
    @picture = Picture.find(params[:id])
    send_data(@picture.data,
              :filename => @picture.name,
              :type => @picture.content_type,
              :disposition => "inline")
  end
end


3. 文件上传初始页面get.html.erb
<%= error_messages_for("picture" ) %>
<% form_for(:picture,
			:url => {:action => 'save'},
			:html => { :multipart => true }) do |form| %>
	Comment: <%= form.text_field("comment" ) %><br/>
	Upload your picture: <%= form.file_field("uploaded_picture" ) %><br/>
	<%= submit_tag("Upload file" ) %>
<% end %>



4. 上传后的从数据库中读取图片并显示图片的页面show.html.erb
<h3><%= @picture.comment %></h3>
<img src="<%= url_for(:action => 'picture', :id => @picture.id) %>"/>


5. 访问http://localhost:3000/upload/get

  • 大小: 6.9 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics