how to read a User uploaded file, without saving it to the database

后端 未结 2 1103
甜味超标
甜味超标 2020-12-01 02:50

I\'d like to be able to read an XML file uploaded by the user (less than 100kb), but not have to first save that file to the database. I don\'t need that file past the curr

相关标签:
2条回答
  • 2020-12-01 03:09

    I need to read yaml files. I use remotipart and here the code:

    in html.slim

     =form_tag('/locations/check_for_import', method: :post, remote: true, multipart: true)
    

    ...

    <input id="uploadInput" type="file" name="uploadInput">
    

    in controller

    content = File.read(params[:uploadInput].tempfile)
    doc = YAML.load(content)
    
    0 讨论(0)
  • 2020-12-01 03:29

    You are very close. Check the class type of params[:uploaded_file], it should typically be either a StringIO or a Tempfile object -- both of which already act as files, and can be read using their respective read method(s).

    Just to be sure (the class type of params[:uploaded_file] may vary depending on whether you are using Mongrel, Passenger, Webrick etc.) you can do a slightly more exhaustive attempt:

    # Note: use form validation to ensure that
    #  params[:uploaded_file] is not null
    
    file_data = params[:uploaded_file]
    if file_data.respond_to?(:read)
      xml_contents = file_data.read
    elsif file_data.respond_to?(:path)
      xml_contents = File.read(file_data.path)
    else
      logger.error "Bad file_data: #{file_data.class.name}: #{file_data.inspect}"
    end
    

    If, in your case, it turns out that params[:uploaded_file] is a hash, make sure that you have not mistakingly flipped the object_name and method parameters when invoking file_field in your view, or that your server is not giving you a hash with keys like :content_type etc. (in which case please comment on this post with the Bad file_data ... output from development.log/production.log.)

    0 讨论(0)
提交回复
热议问题