Rails ActiveStorage 直接上传到本地主机

Rails ActiveStorage direct uploads on localhost

使用Rails 5.2 rc1,在开发中是否可以在本地主机上直接上传?

这是我的表格new.html.erb

<div class="form-group">
  <%= f.label :images %>
  <%= f.file_field :images, multiple: true, direct_upload: true, class: 'form-control' %>
</div>

这是我在控制台中得到的错误:

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

对于将来遇到此问题的任何其他人:

我在我的控制器中误用了这个:

def create
  @post = Post.new(post_params)
  @post.images.attach(post_params[:images]) # THIS WAS THE ERROR!!!

  respond_to do |format|
    if @post.save
      format.html { redirect_to @post, notice: 'Post was successfully created.' }
      format.json { render :show, status: :created, location: @post }
    else
      format.html { render :new }
      format.json { render json: @post.errors, status: :unprocessable_entity }
    end
  end
end

创建新的 post 附加已附加的图像会导致各种错误,例如损坏的 PG 密钥和无效的签名。

确保在新创建的模型实例上上传文件时省略 attach

我运行进入同样的错误信息(rails 5.2.1).

问题是我的浏览器只是将文件名作为字符串提交,而不是上传文件。

发生这种情况是因为我试图向文件输入添加 style="display: none;" 属性,这在尝试设置上传按钮样式时很常见。不确定为什么浏览器 (chrome) 会这样。解决方案是不使用 display:none,而是使用 css opacity=0 设置按钮样式。

不要这样做:

<label class="btn btn-primary btn-file">
    Custom element to upload an image, hurray!
    <%= f.file_field :avatar, accept: "image/*", style: "display: none;" %>
</label>

相反,使用 CSS 隐藏默认浏览器按钮。有关演示,请参阅 here