[英]How to upload a file in 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
我的模型文件是(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):
<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(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
<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
問題的原因是編碼問題。 您似乎正在以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) }
另一個很好的選擇是carrierwave ,安裝非常簡單,github上的指南可以在幾分鍾內啟動並運行。 將它添加到您的gemfile然后運行bundle install
關於這個問題,還有一個很好的軌道廣播
用“wb”代替“wp”。 有用
File.open(path, "wb") { |f| f.write(upload['datafile'].read)}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.