首页 文章

通过Rails 5 API和Active Storage接受图像

提问于
浏览
2

我正在尝试将图像发送到我的Rails应用程序,然后通过Active Storage存储它们 .

我尝试了Base64并直接上传和研究了几个小时,但没有什么真正有效 .

有人能指出我的好方法吗?

我的最后一次尝试是像这样使用Base64:

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

但这导致 "\xAB" from ASCII-8BIT to UTF-8 error.

如果它的Base64或别的东西真的不在乎,我只需要一种方式:-)

1 回答

  • 0

    这是有效的,我直接使用 IO 因为 ActiveStorage 无论如何都需要它 .

    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
    

相关问题