无法将图像上传到活动存储

Can't upload image to active storage

我无法使用 ActiveStorage 存储 base64 文件,我从我的客户端收到一个 base64 字符串

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

当我尝试附加它时,我得到:

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

我看了很多教程,先尝试解码:

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

以及从字符串中删除数据:image/png;base64 部分:

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

然后附加图像但没有成功,当我直接从文件中执行时:

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

它工作得很好,所以我认为我的错误是在解析字符串的过程中

我不确定它是否可行,但请尝试使用此方法创建临时文件 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