为什么在Rails 4.2中上传的jpg文件总是47字节?

时间:2016-01-11 03:24:52

标签: ruby-on-rails file-upload

以下是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有什么问题?

1 个答案:

答案 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