简体   繁体   English

Rails-使用Javascript / HTML上传文件

[英]Rails - File upload with Javascript/HTML

I am trying to upload a file and parse it to rails. 我正在尝试上传文件并将其解析为rails。 I also want to put the content of the file in a sortable table. 我还想将文件的内容放在可排序的表中。 I followed http://railscasts.com/episodes/396-importing-csv-and-excel?autoplay=true and got through it. 我遵循了http://railscasts.com/episodes/396-importing-csv-and-excel?autoplay=true并通过了它。

My View file - index.html.erb looks like this - 我的视图文件-index.html.erb看起来像这样-

<%= form_tag import_users_path, multipart: true do %>
Import a file
<%= file_field_tag :file %>
<%= submit_tag "Submit" %>
<% end %>

*_controllers.rb looks like this * _controllers.rb看起来像这样

class UsersController < ApplicationController
 def index
  @users = User.order(params[:sort])
 end 

 def show
  @user = User.find(params[:id])
 end

 def import
  User.import(params[:file])
  redirect_to action: 'index'
 end
end

Now I want to add styling to the file upload button using Javascript/Bootstrap. 现在,我想使用Javascript / Bootstrap将样式添加到文件上传按钮。 I changed the index.html.erb to the following - 我将index.html.erb更改为以下内容-

<%= form_tag import_users_path, multipart: true do %>
<span class="fileUpload btn btn-primary"> Upload
    <input id="uploadBtn" type="file" class="upload" />
</span>
<%= submit_tag "Submit">
<% end %>

and now assets/javascripts/*.js looks like this - 现在资产/javascripts/*.js看起来像这样-

document.getElementById("uploadBtn").onchange = function() {
document.getElementById("uploadFile").value = this.value;
};

This is not working because the uploaded file is not being parsed as ':file' is not assigned anything. 这不起作用,因为未将上载的文件解析为':file'没有分配任何内容。

How can I apply CSS and javascript styling to 'file_field_tag'? 如何将CSS和javascript样式应用于“ file_field_tag”?

  1. You should be able to add css styling to the tag the same way you could use for your form helpers as such: 您应该能够像使用表单助手一样向标签添加css样式:

    file_field_tag :file, class: 'whatever-class'

  2. While using your hand-written file input, I think you're not getting a value in your controller because you didn't name your field, fix should be simple as: 在使用手写文件输入时,我认为您没有在控制器中获得任何值,因为您没有为字段命名,因此修复应该很简单:

    <input id="uploadBtn" type="file" class="upload" name='file' />

  3. I know you can upload file via AJAX/JS but I don't think the process is that straight-forward as I think you'd need to do some custom form serializations using FormData and other stuff like that. 我知道您可以通过AJAX / JS上传文件,但是我认为过程并不那么简单,因为我认为您需要使用FormData和类似的东西进行一些自定义表单序列化。 Not totally confident that I'm right though! 并不是完全相信我是对的!

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

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