POST file as multipart / form-data for the Rails API

RoR noob is here ... :)

I need to create a Rails API that clients can call and send an XML file through a POST request.

I created my route as follows:

  namespace :api do
      namespace :v1 do
        resource :report
      end
  end

and my controller:

class Api::V1::ReportsController < ApplicationController

  respond_to :xml

  def create
    @report_submission = ReportSubmission.create :login => params[:login],
                                                 :status => :success
    respond_with(@report_submission)
  end
end

What do I need to do in the controller to get the XML file that will be sent by the client, and then read the contents so that I can eventually put it in the database?

How can I check this?

I created a sandbox project to try it and stuck ... I don’t know what to do next. I clicked here:

https://github.com/claudiolassala/api-samples/

Any help would be amazing! end

+5
source share
2 answers

, . GitHub .

, , :

class Api::V1::ReportsController < ApplicationController

  respond_to :xml

  def create

    @report_submission = ReportSubmission.create :login => params[:login],
                                                 :status => :success,
                                                 :results => read_file_data(params[:reportxml])
    respond_with(@report_submission)
  end

  private
    def read_file_data(file)
      xml_contents = ""
      if file.respond_to?(:read)
        xml_contents = file.read
      elsif file.respond_to?(:path)
        xml_contents = File.read(file.path)
      else
        logger.error "Bad file_data: #{file.class.name}: #{file.inspect}"
      end
      xml_contents
    end
end

, , :

When /^I send a POST request containing the file$/ do
  @login = "some-login"
  @file_path = "#{::Rails.root.to_s}/features/step_definitions/test_report.xml"

  post "api/v1/report.xml?login=#{@login}",
       :reportxml => Rack::Test::UploadedFile.new(@file_path, 'text/xml')
end

, , . !

+4

, , 100% , :) RESTfull- params xml. ActiveResource .

, Rails xml .

, , - xml , .

http://apidock.com/rails/ActiveResource/Base , (, xml ActiveResource)

Railscast ActiveResource http://railscasts.com/episodes/94-activeresource-basics http://railscasts.com/episodes/95-more-on-activeresource

, , ,

0

All Articles