
Specifications
- Website with Ruby on Rails (Rails version 3.2.6)
- Mobile Application Developed with PhoneGap (version 2.4.0)
Scenario
The mobile application needs to pass an image captured from the mobile device towards the website. The website then needs to save it for displaying purposes.The
camera.getPicture
function, which is available on PhoneGap, opens the device's default camera so that the user can take a picture. By default, this function returns a string
containing Base64 encoded image data.Application to the Code
Using the Base64 encoded data, we can send this information to the server using an AJAX function and submitting the image data as akey-value
pair.Submitting to the server via AJAX might look similar to this code:
$.ajax({ type: "POST", url: [REPLACE WITH URL TO WHERE THE REQUEST SHOULD BE SENT], data: { imgData: [REPLACE WITH THE BASE64-IMAGE-DATA] }, dataType: "text", timeout: 10000 }).fail(function(jqXHR, status) { // do some checking here }).done(function(jqxHR, status){ // do some checking here });
On the server side, you can catch this data and do the process of saving of an image. See code below as an example:
Controller
def upload_image # this is to verify if the correct if params[:imgData] && !params[:imgData].blank ImageHandler.save_image(params[:imgData]) result = {:message => "Image Saved", :save_status => 0} else result = {:message => "Data is invalid", :save_status => 1} end respond_to do |format| format.xml { render xml: result} format.json { render json: result} end end
Model (app/assets/models/image_handler.rb)
class ImageHandler < ActiveRecord::Base def save_image(imgData) directory = "public/data/" if !File.exists?(directory) Dir.mkdir(directory) end path = File.join(directory, "image.png") File.open(path, 'wb') do|f| f.write(Base64.decode64(imgData)) end end endData sent over AJAX will be handled on the controller. In the controller, we check whether the
imgData
are sent. If yes, pass the imgData
to the model and do the saving process else, we need to return an error message.For the model, the
imgData
passed would be decoded and written as file inside the public/data
directory. This way, the data can now be displayed as a normal image for websites using the imgage_tag
by rails or just by using a simple image tags in HTML.As for the mobile application, an XML result will be sent back for checking whether the process is done successfully.
No comments :
Post a Comment