【问题标题】:carrierwave works with form but not API in Rails 5在 Rails 5 中,carrierwave 可以使用表单,但不能使用 API
【发布时间】:2017-11-19 16:52:50
【问题描述】:

我正在使用 carrierwave 来接受来自 Python API 的图像。我有以下代码:

  def create
    @person = Person.new(person_params)

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

def person_params
  params.permit(:client_file_name, :name, :picture)
end

我不得不删除params.require(:person),因为我使用的名为requests 的Python 库不允许您以这种形式发送文件。

根据服务器日志,图片正在保存中:

Started POST "/people" for 127.0.0.1 at 2017-11-19 11:49:19 -0500
Processing by PeopleController#create as */*
  Parameters: {"picture"=>#<ActionDispatch::Http::UploadedFile:0x007fe5e8e900b8 @tempfile=#<Tempfile:/var/folders/77/2f_jjrld0dxgq3t8xv6clvph0000gn/T/RackMultipart20171119-13141-1nunpha.png>, @original_filename="Phil.png", @content_type=nil, @headers="Content-Disposition: form-data; name=\"picture\"; filename=\"Phil.png\"\r\n">}
   (0.0ms)  begin transaction
  SQL (0.2ms)  INSERT INTO "people" ("picture", "created_at", "updated_at") VALUES (?, ?, ?)  [["picture", "Phil.png"], ["created_at", "2017-11-19 16:49:19.776189"], ["updated_at", "2017-11-19 16:49:19.776189"]]
   (0.6ms)  commit transaction
Redirected to http://localhost:3000/people/8
Completed 302 Found in 15ms (ActiveRecord: 1.5ms)

我只在本地执行此操作。当我查看应该保存图像的目录时,那里有一个名为Phil.png 的图像,除了图像的字节为零外,应该会发生这种情况。

当我使用表单上传同一张图片时,一切正常。我该如何解决这个问题?

【问题讨论】:

  • 我不确定它是否相关。编码类型是multipart/form-data?我曾经遇到过类似的问题,但不记得是否有 0bytes 的图像。

标签: ruby-on-rails ruby-on-rails-5 carrierwave strong-parameters rails-api


【解决方案1】:

所以我想通了。 Rails 要求您将内容类型设置为image/png,因此将其添加到请求中解决了问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-14
    • 2016-06-18
    • 1970-01-01
    • 2017-01-02
    • 2014-08-25
    • 2017-05-24
    • 1970-01-01
    • 2015-04-18
    相关资源
    最近更新 更多