Thoughts, information and reflections about technology

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

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.

 

Similar Posts:

Leave a Reply

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

Contact me
Archives
Categories
Amazon Disclosure

We are a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for us to earn fees by linking to Amazon.com and affiliated sites.