rubymultipartwebmachine

How to accept a PUT multipart file in webmachine-ruby


I am trying to upload a file to a webmachine resource using PUT. The idea is to update the template resource with a file_id.

module App::Resources
  class UpdateTemplateResource < TemplateResource

    def allowed_methods
      %W(PUT)
    end

    def content_types_accepted
      # What to do here?
    end

    private

    def template_id
      request.path_info[:id]
    end

    def template
      @template ||= ::App::Models::Template.find_latest_version_by_guid(id)
    end
  end
end

I have found examples to accept a json type request, but not multipart. The file is not saved in the server but converted and send to another service for storage.


Solution

  • The Webmachine::Request object has body included which is essentially the multipart request with boundaries. If we know what type of file is being send, we could parse it.

    The body boundary includes content type, filename, and param associated with it. Then starts the actual file.

    If JSON

    lines = []
    request.body.to_io.each {|l| lines << l if l =~ /\[/ }
    json = JSON.parse(lines[0])
    

    If pdf file

    lines = request.body.to_io.read
    pdf_as_string = lines.match(/^(\%PDF-)(.*\s)*(\%\%EOF\s)$/)[0]