如何在 ruby on rails 中上传文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11342338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to upload a file in ruby on rails?
提问by Vivacity InfoTech
I'm very new in ruby on rails. I'm stuck with a problem. I want to make a file upload functionality through which I can upload any kind of file (text,image etc.). My controller file is (upload_controller.rb):
我对 ruby on rails 很陌生。我遇到了一个问题。我想做一个文件上传功能,通过它我可以上传任何类型的文件(文本、图像等)。我的控制器文件是(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
My Model file is (data_file.rb):
我的模型文件是(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
My View file is (uploadfile.html.erb):
我的视图文件是(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 %>
Now when I try to upload image then I'm getting error "invalid access mode wp" in model file. When I change File.open(path, "wp") to File.open(path, "w") in model file this give error "'\x89' from ASCII-8BIT to UTF-8". For .txt file, It works fine. I'm using ruby 1.9.3 and rails 3.2.6
现在,当我尝试上传图像时,我在模型文件中收到错误“无效的访问模式 wp”。当我在模型文件中将 File.open(path, "wp") 更改为 File.open(path, "w") 时,这会给出错误“'\x89' from ASCII-8BIT to UTF-8”。对于 .txt 文件,它工作正常。我正在使用 ruby 1.9.3 和 rails 3.2.6
回答by user1466717
Thank you for example, I study rails too!
谢谢举个例子,我也在学rails!
It works in rails 3.1
它适用于 rails 3.1
My code:
我的代码:
Routes
resources :images do
collection { post :upload_image }
end
Controller
控制器
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
View index.html.erb
查看 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 %>
Model
模型
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
回答by Kashyap
The reason for the issue is encoding problems. It seems that you are reading the file in ASCII-8BIT mode and writing it in UTF-8 which means a conversion needs to take place. And conversion from ASCII-8BIT to UTF-8 isn't straight forward. Alternatively, you can specify binary mode for both reading and writing the files.
问题的原因是编码问题。您似乎正在以 ASCII-8BIT 模式读取文件并以 UTF-8 写入,这意味着需要进行转换。从 ASCII-8BIT 到 UTF-8 的转换并不是直接的。或者,您可以为读取和写入文件指定二进制模式。
upload_file = File.new(<original file>, "rb").read
and
和
File.open(<final uploaded file>, "wb") {|f| f.write(upload_file) }
回答by Anconia
Another great option would be carrierwave, which is very simple to install and the guide on github can have you up and running in a matter of minutes. Add it to your gemfile then run bundle install
另一个不错的选择是carrierwave,它安装起来非常简单,github 上的指南可以让您在几分钟内启动并运行。将它添加到您的 gemfile 然后运行bundle install
There's also a good railscaston the subject
关于这个主题还有一个很好的railscast
回答by flyinrhyno
use "wb" instead of "wp". it works
使用“wb”而不是“wp”。有用
File.open(path, "wb") { |f| f.write(upload['datafile'].read)}

