【问题标题】:How can I get the full path of my selected file in Ruby on Rails?如何在 Ruby on Rails 中获取所选文件的完整路径?
【发布时间】:2011-10-05 08:49:18
【问题描述】:

我已将file_field 放在我的视图中:

<% form_for(:uploaded_file, @feed, :url => {:action=>'copy'}, :html=> {:multipart=>true}) do |f| %>
<%= f.file_field :uploaded_file %> <br>
<%= f.submit "Submit" %>
<% end %>

我的控制器中有一个读取 Excel 文件的方法:

def copy
    file = ""
    book = Spreadsheet.open 'excel_file'
    table = book.worksheet 'excel_sheet'
    table.each do |row|
      file << row
    end
end

请求记录

"authenticity_token"=>"BbQRomTLhiF2O54/G6eHwnnaWbLttUSvo31FO3ZtKoA=", 
"uploaded_file"=>{"uploaded_file"=>#<ActionDispatch::Http::UploadedFile:
 0x27b7ab‌​0 @original_filename="test.xlsx",@content_type="application
 /vnd.openxmlformats-officedocument.spreadsheetml.sheet", @headers=
 "Content-Disposition: form-data; name=\"uploaded_file[uploaded_file]\";
 filename=\"volumetrie.xlsx\"\r\nContent-Type: application/vnd.openxmlformats
 officedocument.spreadsheetml.sheet\r\n", @tempfile=#<File:C:/DOCUME~1/me/
 LOCALS~1/Temp/RackMultipart20110714-524-fy6vu>>}, "commit"=>"Submit"} 

我只是想获取我选择的文件的路径以将其插入到我的 Spreadsheet.open 方法中。错误信息是:没有这样的文件或目录。

我想在我的视图中使用我在file_field 中选择的文件路径,而不是'excel_file' 这是我的Excel 文件的路径。如何使用这个参数?

谢谢!

【问题讨论】:

  • 你是指服务器上文件的完整位置,还是用户机器上文件的完整位置?因为您无法获取有关用户机器的信息
  • 在用户的机器上,但是,如果我不能那样做,用户如何选择要读取并附加到数据库中的 xls 文件? (不需要路径)
  • 哦,用户可以使用浏览器的文件选择器对话框选择文件,但是发送到服务器的只是文件名和文件内容
  • 文件内容是参数:uploaded_file ?还是别的什么?

标签: ruby-on-rails excel import spreadsheet


【解决方案1】:

File.absolute_path(文件)

Ruby Doc

【讨论】:

  • 我在哪里使用参数?
【解决方案2】:

在现代浏览器中,您无法从表单中获取文件路径。您只能使用 tempfile 应该以 params[ :uploaded_file ][ :tempfile ] 的形式提供

编辑尝试

file = Spreadshet::Excel.new('params[ :uploaded_file ][ :filename ]', 'w+')
file.write( params[ :uploaded_file ][ :tempfile ].read )

【讨论】:

  • 对不起,我真的是 Rails 新手,我只是想获取我选择的文件的路径,以便将其插入我的 Spreadsheet.open 方法中......
  • 好的。我尝试了很多不同的东西,但我没有发现问题。执行您告诉我的操作后,我总是收到此错误消息。 undefined method 'new' for Spreadsheet:Module 谢谢!
猜你喜欢
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
  • 2015-09-13
  • 2013-07-08
  • 2013-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多