如何在rails上的ruby上传文件?

我在铁轨上的ruby很新。 我遇到了问题。 我想创建一个文件上传function,通过它我可以上传任何类型的文件(文本,图像等)。 我的控制器文件是(upload_controller.rb):

class UploadController  'app\views\upload\uploadfile.html.erb' end def uploadFile post = DataFile.save(params[:upload]) render :text => "File has been uploaded successfully" end end 

我的模型文件是(data_file.rb):

 class DataFile < ActiveRecord::Base attr_accessor :upload def self.save(upload) name = upload['datafile'].original_filename directory = 'public/data' # create the file path path = File.join(directory,name) # write the file File.open(path, "wp") { |f| f.write(upload['datafile'].read)} end end 

我的View文件是(uploadfile.html.erb):

 

File Upload

'uploadFile'}, :multipart => true) do %>

现在,当我尝试上传图像时,我在模型文件中收到错误“无效访问模式wp”。 当我在模型文件中将File.open(path,“wp”)更改为File.open(path,“w”)时,这会将“’\ x89’从ASCII-8BIT”更改为UTF-8“。 对于.txt文件,它工作正常。 我正在使用ruby 1.9.3和rails 3.2.6

谢谢你,我也研究过rails!

它适用于rails 3.1

我的代码:

 Routes resources :images do collection { post :upload_image } end 

调节器

 class ImagesController < ApplicationController def index @car = Car.find(params[:car_id]) @images = @car.images.order("order_id") end def upload_image DataFile.save_file(params[:upload]) redirect_to images_path(:car_id => params[:car_id]) end 

查看index.html.erb

 

File Upload

<%= form_tag({:action => 'upload_image', :car_id => @car.id}, :multipart => true) do %>

<%= file_field 'upload', 'datafile' %>

<%= submit_tag "Upload" %> <% end %> <% @images.each do |image| %> <%= image.id %>
<%= image.name %> <% end %>

模型

 class DataFile < ActiveRecord::Base attr_accessor :upload def self.save_file(upload) file_name = upload['datafile'].original_filename if (upload['datafile'] !='') file = upload['datafile'].read file_type = file_name.split('.').last new_name_file = Time.now.to_i name_folder = new_name_file new_file_name_with_type = "#{new_name_file}." + file_type image_root = "#{RAILS_CAR_IMAGES}" Dir.mkdir(image_root + "#{name_folder}"); File.open(image_root + "#{name_folder}/" + new_file_name_with_type, "wb") do |f| f.write(file) end end end 

问题的原因是编码问题。 您似乎正在以ASCII-8BIT模式读取文件并以UTF-8编写,这意味着需要进行转换。 从ASCII-8BIT到UTF-8的转换并不是直截了当的。 或者,您可以为读取和写入文件指定二进制模式。

 upload_file = File.new(, "rb").read 

 File.open(, "wb") {|f| f.write(upload_file) } 

使用“wb”而不是“wp”。 有用

 File.open(path, "wb") { |f| f.write(upload['datafile'].read)} 

另一个很好的选择是carrierwave ,安装非常简单,github上的指南可以让你在几分钟内启动并运行。 将它添加到您的gemfile然后运行bundle install

关于这个问题还有一个很好的轨道广播