pizza247
pizza247

Reputation: 3897

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:

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)

What am I missing here?

Upvotes: 2

Views: 956

Answers (2)

Jonathan Buyco
Jonathan Buyco

Reputation: 221

You can ignore the file extension check by ignoring the 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.

Upvotes: 3

pizza247
pizza247

Reputation: 3897

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!

Upvotes: 0

Related Questions