December 14

0 comments

Showing the file name before committing to an upload of a CSV file in Ruby on Rails

By Christopher Mendla

December 14, 2017


Last Updated on September 16, 2020 by Christopher G Mendla

I was working with a Rails App where the user would select a category for an upload and then upload the CSV file. I wanted to show the user which category they selected along with the file they are attempting to upload.

This, of course, had to be done outside of Rails with Javascript/jQuery.

The general outline was :

  • Use an onclick to write the selected category to a Javascript variable
  • Get the filename with Javascript (Thanks to a Stack Overflow user)
  • Show an alert box with the category and file name.
  • If all is OK, then the user presses the submit button.
The category is selected via a radio button. The code is something like
 <%= radio_button_tag :data_type, "cars", false, onclick: "setFileType('Cars');"%>
  • The onclick calls a javascript_tag with the setFileType function.
  • The category is passed as a variable.
The javascript_tag with the function is
<%= javascript_tag do %>
  function setFileType(category) {
    file_to_upload = category;
  }
<% end %>
  • The category is passed in as a parameter
  • file_to_upload is set to the catgory
  • (I could probably streamline things by eliminating this step)
The user then selects the file to upload
<%= file_field_tag 'data_file' %>

There is some Javascript that is loaded that looks for events such as a change.

<%= javascript_tag do %>
 $(document).ready(function(){
 $('#data_file').on('change', function(ev) {
   alert("Name: " + ev.target.files[0].name + "n nType: " +
   file_to_upload + "n n Click the UPLOAD (Step 3) button if 
   this is correct");
   });
  });
<% end %>
  • This builds a dialog box with three lines
    • The file name being uploaded
    • The category selected
    • A reminder to click on UPLOAD if they want the file uploaded.
  • n tells Javascript to insert a new line in the dialog box. I have found that the alert statements seem to need to be all on one line
  • The ev.target.files[0].name code was provided by a Stack Overflow user in response to my question on how to do this. This will show the file name selected to be uploaded.

After the user clicks OK and then UPLOAD, the file is uploaded. If they don’t want to upload, they simply don’t click UPLOAD.

This code can probably be improved by having it on page with a div refresh instead of a dialog box.

 

Christopher Mendla

About the author

Leave a Reply

Your email address will not be published. Required fields are marked

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}