Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveStorage to upload large base64 encoded string?

If I have an image that was edited/generated using JavaScript on the client (for example, a cropped photo or the result of a canvas drawing), is there a way to upload it using ActiveStorage?

It would typically be a large string containing "<img src='data:image/jpeg;base64,...=='>" that is stored in a JavaScript variable, not a file.

like image 719
Mike Sax Avatar asked May 02 '18 17:05

Mike Sax


People also ask

Is there a limit to Base64 encoding?

The schema is SYSTOOLS. A character expression to be encoded. The maximum length in 2732 characters.

What is the maximum size of Base64 data that can be decoded?

about 4 or 8kb.

How many bytes is a Base64 string?

Length of data Base64 uses 4 ascii characters to encode 24-bits (3 bytes) of data.

Why is Base64 encoding so long?

The trick behind base64 encoding is that we use 64 different ASCII characters including all letters, upper and lower case, and all numbers.


2 Answers

In addition to Diego Carrion's answer

I did like this.

class Booking < ApplicationRecord
  ...
  has_one_attached :signature
  ...


module Api
  module V1
    class BookingsController < Api::V1::ApiController
    ...
    
      def confirm_hire_details
        booking = current_user.bookings.find(params[:id])

        if booking.update(booking_params.merge(
          {
            signature: signature_decoded
          }
        ))
          ...
        else
          ...
        end
      end

      private

      def signature_decoded
        decoded_data = Base64.decode64(params[:signature].split(',')[1])
        {
          io:           StringIO.new(decoded_data),
          content_type: 'image/jpeg',
          filename:     "signature-#{Time.current.to_i}.jpg"
        }
      end
like image 157
illusionist Avatar answered Oct 21 '22 11:10

illusionist


I did it without the gem.

          Model.create!(
            product: product,
            attachment: { 
              io: StringIO.new(Base64.decode64(params[:product][:base_64_image].split(',')[1])),
              content_type: 'image/jpeg',
              filename: 'image.jpeg'
            }
          )
like image 22
joeyk16 Avatar answered Oct 21 '22 09:10

joeyk16