uploading a file to Rails JSON API server with Paperclip and Multipart request

泄露秘密 提交于 2019-12-02 18:26:46

The pure json way to do this is to not pass content-type multipart-form and pass the file as a base64 encoded string in the json.

I figured this out thanks this post: http://www.rqna.net/qna/xyxun-paperclip-throws-nohandlererror-with-base64-photo.html

Here's an example of the json:

"{\"account\":{\"first_name\":\"John\",\"last_name\":\"Smith\",\"email\":\"john@test.com\",\"password\":\"testtest\",\"avatar\":{\"data\":\"INSERT BASE64 ENCODED STRING OF FILE HERE\",\"filename\":\"avatar.jpg\",\"content_type\":\"image/jpg\"}}}"

Then in the controller process the incoming avatar like this before saving the model.

def process_avatar
  if params[:account] && params[:account][:avatar]
    data = StringIO.new(Base64.decode64(params[:account][:avatar][:data]))
    data.class.class_eval { attr_accessor :original_filename, :content_type }
    data.original_filename = params[:account][:avatar][:filename]
    data.content_type = params[:account][:avatar][:content_type]
    params[:account][:avatar] = data
  end
end
Kevin Dickerson

So, I'm guessing your Post model looks something like this:

class Post < ActiveRecord::Base
  has_attached_file :photo, :styles => { ... }
  ...
end

So you should be able to do something as simple as this:

@post.photo = params[:IMAGEDATA] if params[:IMAGEDATA].present?
@post.save if @post.valid?

And it should save the photo.

If you need to do something more complicated, try re-arranging the form data into the data that the format Paperclip expects. And if you need to dig deeper, take a look inside Paperclip's Paperclip::Attachment class.

Stack Overflow Cross-Reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!