首页 文章

如何使用Active Storage存储URL中的图像

提问于
浏览
1

我的问题是:当我使用Active Storage时,如何从URL上传图像 . 我在Stackoverflow中使用了其他post中的代码,但是通过模型方法,我需要存储在我的表中的param . 奇怪的是,我收到了下一个错误:

ActiveSupport::MessageVerifier::InvalidSignature in PostsController#update

但是当我重新加载节目视图时,从这个模型中,图像会显示存储并部署在我的帖子视图中 .

这里我的代码在 Post model

class Post < ApplicationRecord
  require 'open-uri'

  has_one_attached :image_one
  has_one_attached :image_two
  has_one_attached :url_image

  before_save :grab_image

  
  def grab_image(url)
    downloaded_image = open(url)
    self.url_image.attach(io: downloaded_image, filename: "map.jpg", content_type:"image/jpg")
  end
  
end

这是我在 Controller 的编辑操作中的代码:

def update
    @posturl = params[:post][:url_image]
    @post.grab_image(@posturl)
    respond_to do |format|
      if @post.update!(post_params)
        format.html { redirect_to @post, notice: 'Post was successfully updated.' }
        format.json { render :show, status: :ok, location: @post }
      else
        format.html { render :edit }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

Apparently, the record is saved but i receive this problem

我有以下链接,谈论从URL上传图像的机会,但是,我不知道我还能做什么:

Active Storage Overview - EdgeGuides

@omnilord/rails-5-2-activestorage-mitigating-adoption-pitfalls

2 回答

  • 1

    也许这适合你:

    file = open(url)
    user.image.attach(io: file, filename: "temp.#{file.content_type_parse.first.split("/").last}", content_type: file.content_type_parse.first)
    
  • 0

    这是一个例子:

    file_url = image[:image_url]
    download = open(file_url)
    IO.copy_stream(download,
    user.image.attach(
      io: download,
      filename: image[:name],
      content_type: image[:content_type],
    ))
    

相关问题