Search code examples
javascriptruby-on-railsreact-nativepaperclip

How to submit a base64 encoded file to paperclip?


I have a react native application which reads an image file from the device as a base64 string and submits it through axios to a rails application. Here's a part of the data that's being submitted:

/9j/4QBYRXhpZgAATU0AKgAAAAgABIdpAAQAAAABAAAAPgESAAQAAAABAAAAAAEBAAQAAAABAAAB4AEAAAQAAAABAAACgAAAAAAAAZIIAAQAAAABAAAAAAAAAAD/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAHgAoADASIAAhEBAxEB/8QAGgABAQEBAQEBAAAAAAAAAAAAAAcGBQECCP/EAEIQAQAAAAcMBwQKAwEBAQAAAAAHERJFg8LSAgMEBQYVFhdUVZKjARMUMmWU0SMxpOIhIiQlJidDUWFxN0GBkbEz/8QAGAEBAQEBAQAAAAAAAAAAAAAAAAUGBAH/xAAmEQEAAAIKAgMBAAAAAAAAAAAAgaEFERUWQkNiY8HhBAYSFCEi/9oADAMBAAIRAxEAPwD8vjbatccbTgHHd2TVrjjacA47uyDEjbatccbTgHHd2TVrjjacA47uyDpQNzxQ11JTbE35e9dnr2/b5PVdk+vJkRxypUmLv9EXv/59EfT1lYn2bD+C4tA2wxOsrE+zYfwXFo1lYn2bD+C4tA2wxOsrE+zYfwXFo1lYn

The problem is, I cannot add this to paperclip directly. What should I do to make it work?


Solution

  • Method in model to attach file(Event in this example):

      def add_picture(picture_64, picture_name)
        picture_data                   = Paperclip.io_adapters.for(picture_64)
        picture_data.original_filename = picture_name
        self.picture = picture_data
      end
    

    Method in controller:

      def create_picture
        if params[:picture]
          picture_params = params[:picture]
          @event.add_picture(picture_params[:file_data], picture_params[:file_name])
        end
      end
    

    In general you just need Paperclip.io_adapters.for(picture_64), that will produce you necessary object that acceptable by Paperclip.