如何上传Ruby on Rails中一个文件?(How to upload a file in ru

2019-07-30 06:18发布

我在红宝石很新的轨道。 我坚持着一个问题。 我想打一个文件上传功能,通过它我可以上传任何类型的文件(文本,图像等)。 我的控制文件(upload_controller.rb):

class UploadController < ApplicationController
def index
    render :file => '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

我的视图文件(uploadfile.html.erb):

<h1>File Upload</h1>
<%= form_tag({:action => 'uploadFile'}, :multipart => true) do %>
<p><label for="upload_file">Select File</label>
<%= file_field 'upload', 'datafile' %></p>
<%= submit_tag "Upload" %>
<% end %>

现在,当我尝试上传图像,然后我在模型文件得到错误“无效的访问模式WP”。 当我在模型文件更改File.open(路径, “WP”),以File.open(路径, “W”),这给错误 “的ASCII-8BIT '\ X89' 为UTF-8”。 对于.txt文件,它工作正常。 我使用Ruby 1.9.3和3.2.6轨道

Answer 1:

感谢您的例子,我研究轨道呢!

它工作在轨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

<h1>File Upload</h1>
  <%= form_tag({:action => 'upload_image', :car_id => @car.id}, :multipart => true) do %>
    <p><label for="upload_file">Select File</label>
    <%= file_field 'upload', 'datafile' %></p>
    <%= submit_tag "Upload" %>
  <% end %>

  <% @images.each do |image| %>
     <%= image.id %><br/>
     <%= 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


Answer 2:

究其原因,问题是编码问题。 看来,您正在阅读的ASCII-8BIT模式下的文件和UTF-8,这意味着转换需要发生写它。 和转换从ASCII-8BIT为UTF-8是不是直线前进。 或者,你可以指定读取和写入文件的二进制模式。

upload_file = File.new(<original file>, "rb").read

File.open(<final uploaded file>, "wb") {|f| f.write(upload_file) }


Answer 3:

使用“白平衡”,而不是“WP”。 有用

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


Answer 4:

另一个伟大的选择是carrierwave ,这是安装非常简单,在GitHub上的指南可以让你在几分钟的事上运行。 它添加到您的Gemfile然后运行bundle install

还有一个好railscast关于这个问题



文章来源: How to upload a file in ruby on rails?