how save image using faraday

223 Views Asked by At

I have author class using active storage.

              class Author < ApplicationRecord
                  has_one_attached :image
              end     

Here is my faraday connection

       conn = Faraday.new(
         url: 'http://localhost:3000/',      
         headers: {'Content-Type' => 
         'application/json','Authorization' => "Bearer 
         qAJiTqIJRou0"}    )      do   |f|

          f.request :multipart
          f.adapter :net_http

       end 

permit params

        def author_params
          params.require(:author).permit(:image, :title, 
                        :full_name)    
        end

post request

             require 'faraday'
             require 'faraday/multipart'

             payload = { author: {title: "lo"} }
             payload[:author][:image] = Faraday::Multipart::FilePart.new(Rails.root.join('app', 'assets',                  

                            'images', 'about.jpg'), 'image/jpeg')

             conn.post('/api/v1/authors', payload.to_json)

My received params

        Unpermitted parameter: :image. Context: { controller: 
        Api::V1::AuthorsController, action: create, request: # 
        <ActionDispatch::Request:0x00007f85583d7860>, params: 
         {"author"=>{"title"=>"foo iiiiiii", "full_name"=>"tony", "image"=>{"content_type"=>"image/jpeg", "original_filename"=>"about.jpg", "local_path"=>"/home/kashif/ticket_plot_api/app/assets/images/about.jpg", "io"=>"#<File:0x00007f78f416abd8>", "opts"=>{}}}, "controller"=>"api/v1/authors", "action"=>"create"} }

Author is saving without image

Is anything wrong?

Thanks

2

There are 2 best solutions below

5
Jan Vítek On

I can see two mistakes here:

  1. You have to open the file you pass to the Faraday::Multipart::FilePart like this:
Faraday::Multipart::FilePart.new(File.open(Rails.root.join('app', 'assets',                  
                                           'images', 'about.jpg')), 
                                'image/jpeg')
  1. You have to move the image into the author object
`payload[:author][:image] = Faraday::Multipart::FilePart.new(...)`
0
Kashiftufail On

i just remove "Content-Type' => 'application/json" from header. This was issue as suggested by @Alex in comment.

 headers: {'Authorization' => "Bearer qAJiTqIJRou0"}    

And working.