HTML:
<form class="form-inline" id="upload_form_<%= model %>" action="<%= url_for action: "index" , controller: :admin %>" method="post" enctype="multipart/form-data" οnsubmit="return validateFile('<%= model.to_s %>')">
<div class="form-group">
<label for="exampleInputEmail1">File:</label>
<input type="file" class="form-control" id="input_<%= model %>" name="file_to_upload">
<input type="hidden" id="input_model" name="input_model" value="<%= model %>" />
<%= tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => form_authenticity_token) %>
<button type="submit" class="btn btn-primary"><i class="fa fa-cloud-upload"></i></button>
</div>
</form>
JAVAScript:
unction validateFile(model)
{
//alert("hi");
//alert(model);
//return false;
var file_id = 'input_'+model ;
//alert(file_id);
//return false;
var path = document.getElementById(file_id).value
//alert(path);
var ext = path.split('.').pop().toLowerCase();
//alert(ext);
if(ext != "csv" || ext =="") {
alert('Invalid file type. Please select a CSV file.');
return false;
}
else {
//alert('right extension!');
return true;
}
}
参考链接:
http://stackoverflow.com/questions/651700/how-to-have-jquery-restrict-file-types-on-upload