【发布时间】:2010-12-03 18:13:14
【问题描述】:
我目前有一个可用的照片上传器,它使用回形针和 aws-s3 gems 创建照片图像。加载器还可以动态添加照片上传字段,因此可以在一次提交时一次上传多个文件。我想要做的是可以选择上传一个 zip 文件,并期望该文件包含照片,并让它通过我创建缩略图、中等大小和原始图像的相同过程来上传单个照片文件.我的模型和控制器非常简单,如果在开发中,可以在本地存储照片,如果在生产中,可以在 s3 上存储照片,只是对视图模板有一点点花哨:
photo.rb
class Photo < ActiveRecord::Base
belongs_to :album
if AppConfig['s3']
has_attached_file :data,
:styles => {
:thumb => "100x100>",
:medium => "500x500>"
},
:storage => :s3,
:default_style => :original,
:bucket => AppConfig['s3']['bucket_name'],
:s3_credentials => { :access_key_id => AppConfig['s3']['access_id'], :secret_access_key => AppConfig['s3']['secret_key'] },
:s3_headers => { 'Cache-Control' => 'max-age=315576000', 'Expires' => 10.years.from_now.httpdate },
:path => "/:class/:id/:style/:filename"
else
has_attached_file :data,
:styles => {
:thumb => "100x100>",
:medium => "500x500>"
},
:storage => :filesystem,
:default_style => :original
end
end
*photos_controller.rb*
class Admin::PhotosController < Admin::AdminController
def index
@photos = Photo.all
end
def show
@photo = Photo.find(params[:id])
end
def new
@photo = Photo.new
end
def create
@photo = Photo.new(params[:photo])
if @photo.save
flash[:notice] = "Successfully created photo."
redirect_to [:admin, @photo]
else
render :action => 'new'
end
end
def edit
@photo = Photo.find(params[:id])
end
def update
@photo = Photo.find(params[:id])
album = @photo.album
if @photo.update_attributes(params[:photo])
flash[:notice] = "Successfully updated photo."
redirect_to [:admin, @photo]
else
redirect_to edit_admin_album_url(album)
end
end
def destroy
@photo = Photo.find(params[:id])
album = @photo.album
@photo.destroy
flash[:notice] = "Successfully destroyed photo."
redirect_to edit_admin_album_url(album)
end
end
视图中有趣的部分在这里:
*_form.html.haml*
#photos
- if @album.new_record?
= render :partial => 'photo', :locals => { :form => f, :photo => @album.photos.build }
- else
- for photo in @album.photos
.photo
= link_to(image_tag(photo.data(:thumb)), photo.data(:medium), :class => 'photo_link')
- f.fields_for @album.photos do |photo_field|
/ Viewable?
/ = photo_field.check_box :viewable
%br
= link_to "Delete", [:admin, photo], :confirm => 'Are you sure?', :method => :delete
.float_clear
= add_object_link("New Photo", f, @album.photos.build, "photo", "#photos")
.row
= submit_tag "Save", :disable_with => "Uploading please wait..."
.float_clear
*_photo.html.haml*
.photo_form
%p
- form.fields_for :photos, photo, :child_index => (photo.new_record? ? "index_to_replace_with_js" : nil) do |photo_form|
= photo_form.file_field :data
= link_to_function "delete", "remove_field($(this), ('.photo_form'))"
%br
欢迎所有想法或贡献!谢谢!
【问题讨论】:
标签: ruby-on-rails zip amazon-s3 paperclip photo