开发者

How to read form-data with ruby

In my controller the result of request.body.read is:

=============
--AJAX-----------------------1267183973160
Content-Disposition: form-data; name="1261400603_page_white_word.png"; filename="1261400603_page_white_word.png"开发者_如何学运维
Content-Type: application/octet-stream

thefile
--AJAX-----------------------1267183973160
Content-Disposition: form-data; name="1261400536_page_white_excel.png"; filename="1261400536_page_white_excel.png"
Content-Type: application/octet-stream

thefile
--AJAX-----------------------1267183973160--
=============

It contains n form-data (2 in my example), my goal is to loop through the n form-data and get the data name, filename and a file uploaded, in my example I replaced the binary data by thefile.

here is the content of the params hash

{"action"=>"create", "controller"=>"photos", "1265144945_395.jpg"=>#<File:/var/folders/BT/BTpdsWBkF6myaI-sl3+1NU+++TI/-Tmp-/RackMultipart20100226-273-1un364r-0>}

Cheers


Have you considered using paperclip or attachment_fu? They are battle-tested and will do better than using request.body. In any case, you could parse request.body as follows but it's not the best solution.

inputs =  request.body.read.split(/--ajax-+\d+-*/mi)

inputs.each do |input| 
  input.scan(/(.*)[\n\r]{2,4}(.*)/m) do |header, file| 
    header.scan(/name=["'](.*)["'];\s+filename=["'](.*)["']/) do |name, filename|
      puts name
      puts filename
    end
    puts file
  end
end

Edit: So that params parsing is probably the job of Rack::Utils::Multipart.parse_mulitpart. One should probably reuse the regex's from the source of that to parse this a bit more robustly. Also, it looks like rack is creating a tmp file for you of some sort. Can you check the contents of that file?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜