根据此链接,Rails 4 似乎支持 jQuery 文件上传:Gems Ready for Rails 4。
如果您想使用 Paperclip Gem 执行文件上传,请按照我为您准备的指南进行操作。我从 Pranava Swaroop 那里学到了这个方法。
替代解决方案位于以下链接:Stackoverflow: Rails 4 multiple file uploads solution、Stackoverflow: Jquery file upload in rails 4
1- 将名为“image”的属性添加到您的 RealEstateListing 资源。然后运行 'rake db:migrate' 和/或 'rake db:migrate RAILS_ENV=development' 以更新您的架构和数据库。
即
class AddImageFieldsToRealEstateListing < ActiveRecord::Migration
def change
add_column :realestatelisting, :image_file_name, :string
add_column :realestatelisting, :image_content_type, :string
add_column :realestatelisting, :image_file_size, :integer
add_column :realestatelisting, :image_uploaded_at, :datetime
end
end
2- 更新您的 Gemfile 并使用 Paperclip gem 和 Amazon Web Services 等服务来上传图像。然后运行 'bundle install' 来更新 Gemfile.lock
gem 'paperclip'
gem 'aws-sdk'
3- 更新您的 RealEstateListing 控制器以确保允许“图像”参数
即
def realestatelisting_params
params.require(:realestatelisting).permit(:name,:image)
end
4- 更新 app/helpers/application_helper.rb
即
def image_for_realestatelisting(house)
if house.image.exists?
image_tag(house.image.url, size:'200x200')
else
image_tag('image.jpg')
end
end
5- 使用图片上传功能更新您的 RealEstateListing 模型
即
has_attached_file :image
validates_attachment :image,
:content_type => { :content_type => ['image/jpeg', 'image/png'] },
:size => { :less_than => 2.megabyte }
6- 使用图片上传字段更新您的 RealEstateListing .html.erb 视图
即创建上传
<div>
<div>
<%= f.label :image %><br/>
<%= f.file_field :image %>
</div>
</div>
<div>
<%= f.submit "Create" %>
</div>
即显示上传
<div>
<%= image_for_realestatelisting(@house) %>
</div>
请注意,Paperclip gem 是一个抽象的 Ruby 库,在此处用于 Ruby on Rails 应用程序中,以降低在名为 RealEstateListing 的 ActiveRecord 模型中上传文件的复杂性。 AWS SDK gem aws-sdk 与 Paperclip gem 结合使用,以提供 API 客户端,用于将图像上传到应用程序以进行模型验证,然后再存储在 Amazon 的 S3 文件托管服务上,以独立扩展应用程序的图像文件资源。
Paperclip gem 的规范包括处理图像文件的类方法选项,如 ActiveRecord 模型属性。 Paperclip 辅助方法 (has_attached_file) 声明了属性符号 :image 和图像文件附件之间的模型关联,而它的辅助方法 validates_attachment 方便地包装了多个属性(即图像文件附件的大小和 MIME 内容类型以防止 XSS攻击)进行验证。