Dallsant
Dallsant

Reputation: 83

Can't upload image to active storage

I am unabe to store a base64 file using ActiveStorage,I am recieving a base64 string from my client

params["image"] = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAREAAABMCAYAAABK84MTAAAABHNCSVQICAgIfAhkl0RVh"

and when I try to attach it I get:

ActiveSupport::MessageVerifier::InvalidSignature(ActiveSupport::MessageVerifier::InvalidSignature):

I've followed many tutorials, tried decoding it first:

decoded_image = Base64.decode64(params["image"])
post.image.attach(decoded_image)

As well as removing the data:image/png;base64 part from the string with:

decoded_image = Base64.decode64(params["image"]['data:image/png;base64,'.length .. -1])

And then attaching the image with no success, when I do it directly from a file with:

file = open("image.png")
post.image.attach(io: file, filename: "post.png")

It works perfectly, so I think that my mistake is during the parsing of the string

Upvotes: 1

Views: 843

Answers (1)

pedrosfdcarneiro
pedrosfdcarneiro

Reputation: 341

I'm not sure if it will work, but give a try to this approach creating a temporary file with Tempfile:

encoded_image = params["image"]['data:image/png;base64,'.length .. -1]
decoded_image = Base64.decode64(encoded_image)

file = Tempfile.new

file.binmode
file.write(decoded_image)
file.rewind

post.image.attach(
  io: file,
  filename: "post.png" # The name of the file should be received from paramaters, as well
)

file.close
file.unlink

Upvotes: 1

Related Questions