【问题标题】:Accept an image via Rails 5 API and Active Storage通过 Rails 5 API 和 Active Storage 接受图像
【发布时间】:2018-08-25 16:16:58
【问题描述】:

我正在尝试将图像发送到我的 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 还是其他什么,我只需要一种方法 :-)

【问题讨论】:

    标签: ruby-on-rails-5 rails-activestorage


    【解决方案1】:

    这行得通,我直接使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-30
      • 2018-06-29
      • 2023-03-12
      • 2019-11-01
      • 2019-01-01
      • 2019-07-13
      • 2018-11-16
      • 2013-10-12
      相关资源
      最近更新 更多