在Rails中简单的文件上传并不起作用

时间:2016-03-07 16:57:51

标签: ruby-on-rails file-upload

我在Rails3和Ruby1.9上有一个应用程序。我想上传一个文件。我一直在尝试一个简单的解决方案,我在这里发布了几个帖子。

表格

=form_for :upload, :html => {:multipart => true} do |f|
   = f.file_field :my_file
   = f.submit "Upload"

控制器

def file_upload
    path = File.join("public/", upload["my_file"].original_filename)
    File.open(path, "wb") { |f| f.write(upload["my_file"].read) }
end

路线

root :to => "pages#index"
resources :pages do
    collection {post :file_upload}
end

当我点击“上传”时,我没有收到任何错误,但该文件未在公共目录中上传。我错过了什么?

1 个答案:

答案 0 :(得分:0)

此解决方案适用于我(reference)。

控制器:将保存目录从公共/上传更改为上传。使用Rails.root来连接路径。

def upload
    uploaded_io = params[:file]
    File.open(Rails.root.join('public', 'uploads',uploaded_io.original_filename), 'wb') do |file|
         file.write(uploaded_io.read)
         respond_to do |format|
             format.html { redirect_to(root_url, :notice => 'File was uploaded.') }
         end
     end
end

表单:将form_for更改为form_tag

=form_tag({action: :upload}, multipart: true) do
    = file_field_tag 'file'
    = submit_tag 'Upload'

路线:

root :to => "pages#index"
resources :pages do
    collection {post :upload}
end