views:

51

answers:

2

Hi,

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

+1  A: 

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?

anshul
well, the data are submitted by an ajax request with sendAsBinary (only Firefox 3) and paperclip doesn't catch the file (don't know why!), see http://stackoverflow.com/questions/2306910/paperclip-and-xhr-sendasbinary and http://stackoverflow.com/questions/2325827/diff-between-xhr-sendasbinary-and-classic-file-submit-in-http-request thanks
denisjacquemin
Oh great.. I had seen the first of those two questions and was wondering what the answer would be...
anshul
A posted the answer here http://stackoverflow.com/questions/2306910/paperclip-and-xhr-sendasbinary/
denisjacquemin
A: 

You can found the answer here http://stackoverflow.com/questions/2306910/paperclip-and-xhr-sendasbinary/

denisjacquemin