我对 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
我的视图文件是(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 %>
现在,当我尝试上传图像时,我在模型文件中收到错误“invalid access mode 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