5

如何通过 curl 发布以将文件(在这种情况下为图像)上传到活动存储?文档没有确切说明如何使用 curl 或 JS(例如 Axios)

像这样的工作(如果我关闭真实性令牌(skip_before_action :verify_authenticity_token)):

 curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST -d '{"image": {"user_id":"1"}}' http://localhost:3000/images.json

这将像正常的 curl JSON 请求一样发布。

像这样在 base64 中编码文件看起来很有希望:

(echo -n '{"image": {"user_id":"1", "picture":"'; base64 /Users/cj/Desktop/DesktopArchive/5vvyo4u8y8wz.jpg; echo '"}}') | curl -v -H "Content-Type: application/json" -H 'Accept: application/json' -X POST -d @-  http://localhost:3000/images.json

虽然我ActiveSupport::MessageVerifier::InvalidSignature在上传时得到了一个。我怀疑 base64 不是正确的签名。我应该使用什么来编码要上传到活动存储的图像?

编辑:

不是通过 JSON,而是通过表单工作:

 curl \
   -F "image[user_id]=1" \
   -F "image[picture]=@/Users/cj/Desktop/DesktopArchive/5vvyo4u8y8wz.jpg" \
   http://localhost:3000/images

但是,您如何通过 json 调用来做到这一点,以便可以通过 Axios 或其他方式完成?

4

1 回答 1

1

我的示例与您的图像模型不同。但是您可以在显示我的示例代码 https://github.com/x1wins/tutorial-rails-rest-api/blob/master/README.md#active-storage后更改代码

模型

class Post < ApplicationRecord
  has_many_attached :files
end

控制器

  # posts_controller
  # POST /posts
  def create
    @post = Post.new(post_params)
    @post.files.attach(params[:post][:files]) if params.dig(:post, :files).present?

    set_category @post.category_id

    if @post.save
      render json: @post, status: :created, location: api_v1_post_url(@post)
    else
      render json: @post.errors, status: :unprocessable_entity
    end
  end

  # PATCH/PUT /posts/1
  def update
    @post.files.attach(params[:post][:files]) if params.dig(:post, :files).present?
    if @post.update(post_params)
      render json: @post
    else
      render json: @post.errors, status: :unprocessable_entity
    end
  end

  # DELETE /posts/:id/attached/:id
  def destroy_attached
    attachment = ActiveStorage::Attachment.find(params[:attached_id])
    attachment.purge # or use purge_later
  end

卷曲

curl -F "post[body]=string123" \
        -F "post[category_id]=1" \
        -F "post[files][]=@/Users/rhee/Desktop/item/log/47310817701116.csv" \
        -F "post[files][]=@/Users/rhee/Desktop/item/log/47310817701116.csv" \
        -X POST http://localhost:3000/api/v1/posts
于 2020-02-11T17:40:16.883 回答