【问题标题】:Curl Post JSON format to ActiveStorage in Rails with image在 Rails 中使用图像将 JSON 格式卷曲到 ActiveStorage
【发布时间】:2018-04-21 18:22:12
【问题描述】:

如何通过 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 或其他方式来实现?

【问题讨论】:

  • 你最终弄清楚了吗?
  • 并非如此。您必须上传表单。
  • 据我所知无法做到
  • 显示您的模型。你在图像模型中使用了 has_many_attached 吗?

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


【解决方案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

【讨论】:

    猜你喜欢
    • 2022-08-20
    • 2020-04-24
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 2018-08-27
    • 2020-03-15
    • 2017-04-09
    • 2021-06-12
    相关资源
    最近更新 更多