ruby script\rails generate scaffold image content:binary width:integer height:integer name:string
I have a database table for storing an uploaded image, including the binary content, the height and width of the image and a name. Now that I have a place to store the image, I need to modify the generated web pages, so I can upload it.
Converting the applications.html file from erb to haml is just a straightforward transformation. Here is what it looks like when I am done:
yield :headon line 8 of the application.html.haml file above. Lines 9-16 are the boilerplate error handling that was generated by the scaffold command. The remainder just generates the HTML for displaying the image and for entering the name of the image.
We are now almost, but not quite, done. If you notice the field that we are storing the image content in is content64, while the database column for the binary data is just called content. We need to take the base64 encoding of the image that is sent over the wire as part of the HTML POST and decode it to binary before saving in the database. To do that, we just need to add new methods in our app/models/image.rb Image class.
1 require "base64" 2 class Image < ActiveRecord::Base 3 def content64 4 return nil unless content 5 return "data:image/png;base64," + Base64.encode64(content); 6 end 7 8 def content64=(c64) 9 index = c64.index(','); 10 self.content = Base64.decode64(c64[index..-1]); 11 end 12 endThis way when the content64 attribute is assigned in our controller class, it'll actually write the binary data to the content field so it can be saved to the database. The only clever part of this is that the content64 data that is passed from the HTML form has the initial string "data:image/png;base64,". Lines 9-10 calculate where this prefix ends and just decodes the remainder of the string. Line 5 adds this prefix back on to the encoded binary content.