0
votes

I am trying to upload a file to grape 0.7.0. I am using FormData and javascript fetch on the frontend.

My request headers looks like

accept:*/*
accept-version:v3
authorization:omitted
content-type:multipart/form-data
Origin:http://dev:3000
Referer:http://dev:3000/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36

My request payload looks like

------WebKitFormBoundaryqiglzdBECLEG1gI3
Content-Disposition: form-data; name="csv"; filename="invitations.csv"
Content-Type: text/csv


------WebKitFormBoundaryqiglzdBECLEG1gI3--

When I check my grape params in the endpoint I get

{"------WebKitFormBoundaryxxY3USBOh0XBBUbk\r\nContent-Disposition: form-data"=>nil,
 "name"=>"\"csv\"",
 "filename"=>
  "\"invitations.csv\"\r\nContent-Type: text/csv\r\n\r\nFirst Last, [email protected]\r\n------WebKitFormBoundaryxxY3USBOh0XBBUbk--\r\n",
 "route_info"=>
  #<Grape::Route:0x0000000a25ce70
   @options=
    {:description=>"Invite via CSV",
     :params=>
      {"csv"=>
        {:required=>false, :type=>"Rack::Multipart::UploadedFile", :desc=>"csv containing users to be invited"}},
     :prefix=>nil,
     :version=>"v3",
     :namespace=>"/invitations",
     :method=>"POST",
     :path=>"/invitations/csv(.:format)",
     :compiled=>/\A\/invitations\/csv(?:\.(?<format>[^\/.?]+))?\Z/}>}

I want the file to be mapped to params[:csv]. Why is grape interpreting the params this way? What am I doing wrong?

Endpoint Declaration:

desc "Invite via CSV"
params do
    optional :csv, type: Rack::Multipart::UploadedFile, desc: 'csv containing users to be invited'
end
post '/csv' do
    binding.pry # here is where I got the above grape params
    # ...
end
1
how is declared your grape resources? please provide more info about your application so we can help you. - Fabiano Arruda
@FabianoArruda added endpoint declaration - Derek

1 Answers

0
votes

I think you need to set the content_type for csv.

class My::API < Grape::API
  content_type :csv, 'text/csv'
end

Use type: File which is just an alias for Rack::Multipart::UploadedFile.

desc "Invite via CSV"
params do
  optional :csv, type: File, desc: 'csv containing users to be invited'
end
post '/csv' do
  params.csv.filename # => 'invitations.csv'
  params.csv.type     # => 'text/csv'
  params.csv.tempfile # => #<File>
end