Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 370
crispychicken Avatar asked Feb 11 '14 16:02

crispychicken


2 Answers

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

like image 178
Tha Leang Avatar answered Sep 27 '22 22:09

Tha Leang


You are whitelisting the filetypes permitted. By default, Carrierwave will attempt to determine the filetype by the filename extension - which isn't being passed since this is actually a Blob object. As such, you're getting a validation error about the file's 'type'. To fix this, simply append the expected filename extension for blob objects:

if params[:image].try(:original_filename) == 'blob'
  params[:image].original_filename << '.png'
end

Image.create!(image: params[:image])
like image 22
PinnyM Avatar answered Sep 27 '22 21:09

PinnyM