rrd
rrd

Reputation: 43

How do I save an image returned by a webservice?

I have a webservice call that will return an image, now I want to save this image to the filesystem in the server.

The problem is, I cannot make the webservice call from the server, as the webservice application runs on each user machine and a request is made to the service as http://localhost/get_image, which returns the image.

How do I save this image on the server?

Upvotes: 2

Views: 2834

Answers (3)

Surbhi Gupta
Surbhi Gupta

Reputation: 56

You can use HTML5 to load image using javascript and send base64 encoded response to sever where you can decode the response and write image to a file. Here is the approach

  1. Create a form with following html elements
    • canvas element: to get the image
    • text area: to store the base 64 encoded response and send response to server
  2. Ensure that the webservice response headers has "Access-Control-Allow-Origin: *" to allow cross origin resource sharing

  3. Jquery code

var myCanvas = document.getElementById('canvasId');    
var ctx = myCanvas.getContext('2d');    
var img = new Image;    
img.crossOrigin = 'anonymous';    
img.src = "web service url which returns image";    
img.onload = function(){
  console.log( img.width, img.height );
  // set canvas height and width to image height and width else only part of image will get created
  myCanvas.height = img.height;    
  myCanvas.width = img.width;    
  ctx.drawImage(img,0,0); // Or at whatever offset you like    
  var dataURL = myCanvas.toDataURL("image/png");    
  dataURL = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");    
  $('#some_text_area_id').val(dataURL); // set the response in text area    
  $('#form_id').submit();   // submit the form
};
  1. Server side - Decode the response using "base64" ruby library
File.open('test.png',"wb") do |file|
  file.write(Base64.decode64(params[:text_area]))
end

Upvotes: 4

crazycrv
crazycrv

Reputation: 2445

As suggested above base64 encoding should be used when transferring image over wire. Base64 represents binary data in an ASCII string format. Its specifically for MIME content transfer encoding and storing complex data in XML.

You can try Javascript base64 encoding decoding here http://rumkin.com/tools/compression/base64.php

Also, make sure you use file.write and file.read instead of file.puts and file.gets when you try to write png image files

File.open('a.png', 'rb') do |infile|
   File.open('b.png', 'wb') do |outfile|
      outfile.write(infile.read)
   end  
end

Though the best solution is to return image URL as web service response and fetch the image from the asset server.

Upvotes: 0

dbKooper
dbKooper

Reputation: 1045

I prefer using carrierwave gem for url image upload

http://railscasts.com/episodes/253-carrierwave-file-uploads?autoplay=true

Upvotes: 0

Related Questions