【发布时间】:2016-02-07 04:39:39
【问题描述】:
我在视图中显示上传的图像时遇到问题。 IMO 由于/public/uploads 中每个上传文件的大小为零。
目前正在尝试掌握上传和提供文件没有任何 ruby/rails gem。
为此,我运行了一个带有基本脚手架的原始应用程序,仅用于测试上传/保存周期:
schema.rb:
ActiveRecord::Schema.define(version: 20151104043709) do
create_table "uploads", force: :cascade do |t|
t.string "filename"
t.string "content_type"
t.binary "content"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
UploadsController#create:
def create
@upload = Upload.new(upload_params)
data = params[:upload][:file]
File.open(Rails.root.join('public', 'uploads', data.original_filename), 'wb') do |f|
f.write(data.read)
end
respond_to do |format|
if @upload.save
format.html { redirect_to @upload, notice: 'Upload was successfully created.' }
format.json { render :show, status: :created, location: @upload }
else
format.html { render :new }
format.json { render json: @upload.errors, status: :unprocessable_entity }
end
end
end
模型上传.rb:
class Upload < ActiveRecord::Base
include ActionView::Helpers::NumberHelper
attr_accessor :upload
def file=(upload_data)
self.filename = upload_data.original_filename
self.content_type = upload_data.content_type
self.content = upload_data.read
end
def filename=(new_filename)
write_attribute("filename", sanitize_filename(new_filename))
end
private
def sanitize_filename(filename)
just_filename = File.basename(filename)
just_filename.gsub(/[^\w\.\-]/, '_')
end
end
上传#显示视图:
<p id="notice"><%= notice %></p>
<p>
<strong>Filename:</strong>
<%= @upload.filename %>
</p>
<p>
<strong>Content type:</strong>
<%= @upload.content_type %>
</p>
<p>
<%= image_tag "/public/uploads/#{@upload.filename}" %>
</p>
<%= link_to 'Edit', edit_upload_path(@upload) %> |
<%= link_to 'Back', uploads_path %> |
<%= link_to 'Download', download_path(id: @upload) %>
问题:不顺利的是所有文件在/public/uploads dir 中都获得了 0 字节。
注意: 二进制文件应该可以正常工作,因为可以使用send_data 下载每个文件:
def download
send_data(@upload.content,
filename: @upload.filename,
content_type: @upload.content_type,
)
end
============================================ 问题:应用程序有什么问题以及如何解决它以显示图像或图像?提前感谢您的帮助!
【问题讨论】:
-
视图中 image_tag 的 HTML 标记:
<img src="/public/uploads/61.JPG" alt="61" /> -
使用其中一颗宝石。严重地。回形针。载波。去做吧。
标签: ruby-on-rails image file-upload