简体   繁体   English

ruby roo gem excel导入错误

[英]ruby roo gem excel import error

I think there's something very simple that I don't see going on here that's wrong. 我认为有一个非常简单的东西,我看不到这里是错的。 Heres My jquery code that's uploading the file: 这是我上传文件的jquery代码:

import: function (e) {
  e.preventDefault();

  var formData = new FormData();
  jQuery.each($('#import_excel_file')[0].files, function(i, file) {
    formData.append('import_file', file, 'xls');
  });
  formData.append('fuel_type_id', $('#import_fuel_type').val());

  this.shipOff(formData);
},

shipOff: function (formData) {
  $.ajax({
    type: 'POST',
    url: App.Options.rootUrl + "/stations/stations/excel_import",
    data: formData,
    cache: false,
    contentType: false,
    processData: false,
    success: function (data) {
    console.log('successful upload', data);
    }
  });
}

Then in the controller, where I call import = Excel.new(xls_file.tempfile.to_path.to_s) , I get an error like TypeError (/var/folders/rd/58f3hjw10lv09q_8hsl0l7zn1mn1rf/T/RackMultipart20130909-36782-r1bv5n is not an Excel file) 然后在控制器中,我称之为import = Excel.new(xls_file.tempfile.to_path.to_s) ,我收到类似TypeError (/var/folders/rd/58f3hjw10lv09q_8hsl0l7zn1mn1rf/T/RackMultipart20130909-36782-r1bv5n is not an Excel file)

What am I missing here? 我在这里想念什么?

You can ignore the file extension check by ignoring the file_warning ( https://github.com/Empact/roo/issues/67 ) 您可以通过忽略file_warning( https://github.com/Empact/roo/issues/67 )来忽略文件扩展名检查。

Roo::Excel.new(file.path, file_warning: :ignore)

I would also recommend moving this logic out of your controller into an importer class. 我还建议将这种逻辑从您的控制器中移出,以导入程序类。

I found this answer which seems to do the trick. 我发现这个答案似乎可以解决问题 Here's what My controller looks like now: 这是我的控制器现在的样子:

def excel_import
  tmp = params['import_file'].tempfile
  tmp_file = File.join("public", params['import_file'].original_filename)
  FileUtils.cp tmp.path, tmp_file

  import = Excel.new(tmp_file)

  # do what I need with the tmp_file here...

  FileUtils.rm tmp_file

  # a response to let ajax know it worked.
  render :json => 'true'
end

If anyone has a better answer that does it the "roo way" please chime in! 如果有人有一个更好的答案,那就是“ roo way”,请注意!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM