用ruby grape上传文件

时间:2016-02-26 23:33:26

标签: ruby-on-rails ruby grape grape-api

我正在尝试将文件上传到grape 0.7.0。我在前端使用FormDatajavascript fetch

我的请求标题看起来像

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

我的请求有效负载看起来像

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


------WebKitFormBoundaryqiglzdBECLEG1gI3--

当我检查端点中的grape参数时,我得到了

{"------WebKitFormBoundaryxxY3USBOh0XBBUbk\r\nContent-Disposition: form-data"=>nil,
 "name"=>"\"csv\"",
 "filename"=>
  "\"invitations.csv\"\r\nContent-Type: text/csv\r\n\r\nFirst Last, firstlast@foobar.com\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/}>}

我希望将file映射到params[:csv]。为什么grape以这种方式解释参数?我做错了什么?

端点声明:

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 个答案:

答案 0 :(得分:0)

我认为您需要为csv设置content_type。

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

使用type: File,它只是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