开发者

How to parse an uploaded txt file in Rails3

开发者 https://www.devze.com 2023-02-11 06:34 出处:网络
I have a form which have a file input; <%form_tag \'/dboss/newsbsresult\' , :remote=>true do %>

I have a form which have a file input;

<%form_tag '/dboss/newsbsresult' , :remote=>true do %>
    <input type="file" id="examsendbutton" name="txtsbs"/><br/>
    <inpu开发者_JAVA技巧t type="submit" value="Gonder">
<%end%>

Here i want the user to select a txt file which i try to parse and use at server, but i cannot catch the uploaded file with this code,

def newsbsresult
        @u = params[:txtsbs] #Or params[:txtsbs].to_s
        p @u
end

What is the true way of achieving this?


AJAX requests do not support file uploads out of the box -- or technically, at all. This is because JavaScript can't read the data from the file field directly (except in HTML 5). There are a number of ways to do AJAX-like file uploads (e.g. file-uploader or uploadify, amongst older techniques), but Rails does not support these by simply setting :remote => true - you have to use something else/additional to get it to work.

The easy solution is to remove :remote => true and add :multipart => true.


Further reading:

  • http://blog.new-bamboo.co.uk/2010/7/30/html5-powered-ajax-file-uploads
  • https://github.com/davesouth/mongoid-carrierwave-uploadify


Try adding :multipart => true to your form_tag

<% form_tag '/dboss/newsbsresult' , :remote=>true, :multipart => true do %>


Based on your question, if my understand is right. you want to read data from the upload file. I was ran in similar thing that need to show uploaded text in the another text area on my Rails application.

Here is what i did.

View

  1 <%= form_tag('/dboss/newsbsresult' , :multipart => true) do %>  
  2   <input type="file" id="examsendbutton" name="txtsbs"/><br/>
  3   <input type="submit" value="Gonder">
  4 <% end %>

Controller

  1   def index
  2     if (params[:txtsbs].present?)
  3       @upload_text = params[:txtsbs].read
  4       render :text => @upload_text
  5    end
  6   end

Route

  match 'dboss/newsbsresult' => 'user#index'
0

精彩评论

暂无评论...
验证码 换一张
取 消