用CarrierWave更新图片

时间:2019-02-14 06:33:24

标签: ruby-on-rails carrierwave cloudinary

我使用CarrierWave通过Cloudinary将图片上传到帖子中

mount_uploader :picture, PostimageUploader

这是文件PostimageUploader:

class PostimageUploader < ::Uploader::Base

  include Cloudinary::CarrierWave
  process :convert => 'png'
  process :tags => ['post_picture']

  version :standart do
    process :resize_to_fill => [100, 150, :north]
  end

  version :thumbnail do
    resize_to_fit(50, 50)
  end

  def public_id
    return model.id
  end

end

当用户加载图片后,js会向服务器调用ajax请求。

formData.append('picture',file)
fetch('http://localhost:3001/posts/image-upload', {
  method: 'POST',
  body: formData
})

在服务器端输入的参数:

Parameters: {"picture"=># 
<ActionDispatch::Http::UploadedFile:0x007fde206e7728 @tempfile=# 
<Tempfile:/var/folders/15/m1lbk9vs6930yn1zyk06wjs40000gn/T/ 
RackMultipart20190214-87479-5hoj5k.png>, @original_filename="Снимок 
экрана 2019-01-30 в 13.31.07.png", @content_type="image/png", 
@headers="Content-Disposition: form-data; name=\"picture\"; 
filename=\"\xD0\xA1\xD0\xBD\xD0\xB8\xD0\xBC\xD0\xBE\xD0\xBA 
\xD1\x8D\xD0\xBA\xD1\x80\xD0\xB0\xD0\xBD\xD0\xB0 2019-01-30 \xD0\xB2 
13.31.07.png\"\r\nContent-Type: image/png\r\n">}

对于上传图片,我使用下一个功能:

post = Post.first

post.update(picture: params[:picture])

render json: {
    status: 200,
    picture: post.picture
}

这不起作用,json返回null。但是,如果我重新加载帖子:

post = Post.first

post.update(picture: params[:picture])
post = Post.first

render json: {
    status: 200,
    picture: post.picture
}

JSON具有指向新图片的URL。我在哪里弄错了?

0 个答案:

没有答案