Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accept an image via Rails 5 API and Active Storage

I am trying to send images to my Rails app and then store them via Active Storage.

I tried Base64 and direct upload and researched for hours but nothing really works.

Can somebody point me to a good way?

My last attempt was to use Base64 like so:

def attach_preview
  page = Page.first
  content = JSON.parse(request.body.read)
  decoded_data = Base64.decode64(content["file_content"].force_encoding("UTF-8"))
  begin
    file = Tempfile.new('test')
    file.write decoded_data
    #page.thumbnail = file
    filename = "foooo"
    page.thumbnail.attach(io: File.read(file), filename: filename)
    if page.save
      render :json => {:message => "Successfully uploaded the profile picture."}
    else
      render :json => {:message => "Failed to upload image"}
    end
  ensure
    file.close
    file.unlink
  end
end

But this results in a "\xAB" from ASCII-8BIT to UTF-8 error.

Dont really care if its Base64 or something else, I just need a way :-)

like image 728
bnassler Avatar asked Oct 23 '25 16:10

bnassler


1 Answers

This works, I use IO directly since ActiveStorage needs it anyway.

def attach_thumbnail
  content = JSON.parse(request.body.read.force_encoding("UTF-8"))
  decoded_data = Base64.decode64(content["file_content"])
  io = StringIO.new
  io.puts(decoded_data)
  io.rewind
  @page.thumbnail.attach(io: io, filename: 'base.png')
  @page.save
  render json: {
    success: @page.thumbnail.attached?,
    thumbnail_url: url_for(@page.thumbnail),
    page: @page
  }
end
like image 108
bnassler Avatar answered Oct 27 '25 02:10

bnassler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!