以下是create
控制器中的uploaded_file
。此处仅显示相关代码部分。要上传的文件在params[:uploaded_file][:file_for_upload]
:
def create
....
uploaded_io = params[:uploaded_file][:file_for_upload]
@uploaded_file.content_type = uploaded_io.content_type
@uploaded_file.size_kb = BigDecimal(uploaded_io.size)/BigDecimal(1024) #KB
@uploaded_file.file_name = uploaded_io.original_filename
@uploaded_file.file_extension = uploaded_io.original_filename.sub(/.+\./, '').downcase()
File.open(Rails.root.join(@uploaded_file.storage_subdir, @uploaded_file.file_name), 'wb') do |file|
file.write(uploaded_io)
end
.....
end
以下是file_for_upload
的视线:
<%= f.input :file_for_upload, as: :file, required: true %>
上传的流程成功运行。 uploaded_io
记录的文件大小是实际大小(xxxKB)。保存的文件格式为jpg
,位于右侧子目录中。但它的大小只有47个字节。上传了一些文件,无论原始大小如何,它们都会结束47个字节。上面的file.write
有什么问题?
答案 0 :(得分:0)
将upload_io
添加到File.open(Rails.root.join(@uploaded_file.storage_subdir, @uploaded_file.file_name), 'wb') do |file|
file.write(uploaded_io.read)
end
后,文件上传工作正常:
int