How to save base64 image in Blob with Carrierwave in Rails4?

crispychicken picture crispychicken · Feb 11, 2014 · Viewed 6.9k times · Source

Like described in this Tutorial, I'm converting a canvas into a DataUrl and this DataUrl into a Blob. Then I make an ajax post request and would like to save the image in the Database using Carrierwave.

This is my JS code:

uploadButton.on('click', function(e) {

  var dataURL = mycanvas.toDataURL("image/png;base64;");

  // Get our file
  var file= dataURLtoBlob(dataURL);

  // Create new form data
  var fd = new FormData();

  // Append our Canvas image file to the form data
  fd.append("image", file);

  // And send it
  $.ajax({
    url: "/steps",
    type: "POST",
    data: fd,
    processData: false,
    contentType: false,
  });
});

// Convert dataURL to Blob object
function dataURLtoBlob(dataURL) {

  // Decode the dataURL
  var binary = atob(dataURL.split(',')[1]);

  // Create 8-bit unsigned array
  var array = [];
  for(var i = 0; i < binary.length; i++) {
    array.push(binary.charCodeAt(i));
  }

  // Return our Blob object
  return new Blob([new Uint8Array(array)], {type: 'image/png'});
}

When I add the following code to my controller, then the Image get's saved but of course not through carrierwave.

File.open("#{Rails.root}/public/uploads/somefilename.png", 'wb') do |f|
  f.write(params[:image].read)
end

Updated Info:

These are the params for my ajax post request:

Parameters: {"image"=>#<ActionDispatch::Http::UploadedFile:0x007feac3e9a8a8 @tempfile=#<Tempfile:/var/folders/0k/q3kc7bpx3_51kc_5d2r1gqcc0000gn/T/RackMultipart20140211-1346-gj7kb7>, @original_filename="blob", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"image\"; filename=\"blob\"\r\nContent-Type: image/png\r\n">}

And these are the params for a standard file upload:

Parameters: {"utf8"=>"✓", "image"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x007feac20c2e20 @tempfile=#<Tempfile:/var/folders/0k/q3kc7bpx3_51kc_5d2r1gqcc0000gn/T/RackMultipart20140211-1346-1ui8wq1>, @original_filename="burger.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"image[image]\"; filename=\"xy.jpg\"\r\nContent-Type: image/jpeg\r\n">}}

If I do Image.create(params[:image]) I have transaction rollback...

Error for transaction rollback:

Unprocessable Entity
ActiveRecord::RecordInvalid (Validation failed: image You are not allowed to upload "" files, allowed types: jpg, jpeg, gif, png)

Answer

Tha Leang picture Tha Leang · Apr 9, 2015

I just wanted to add, you can add the file type in your view while appending your blob.

  // Get our file
  var file = dataURLtoBlob(dataURL);

  // Create new form data
  var fd = new FormData();

  // Append our Canvas image file to the form data
  fd.append("image", file, "blob.jpg");

Note the ending when we define the filename. Hope this helps someone.

Source: https://developer.mozilla.org/en-US/docs/Web/API/FormData/append