davidhu
davidhu

Reputation: 10432

Upload Image via facebook marketing api through browser

I am trying to use the Facebook marketing API SDK to upload images to Facebook.

This is the sdk

I want the user to be able to click to select a file from the browser and run the upload via Rails and the SDK.

Basically, here is the flow I am trying to do.

  1. user select file
  2. click upload
  3. The backend controller processes the request and uploads it to facebook via the API.

However, the issue I am running into is, for security reasons, browsers do not have access to file path, which Facebook SDK asks for.

ad_account.adimages.create({
  'logo1.png' => File.open('./assets/logo1.jpg')
}) 

If I use ActionDispatch::Http::FileUpload that is built into Rails or carrierwave, I get access to the tempfile, which has a name similar to RackMultipart20170803-89798-1e9hr

If I try to upload that to Facebook, I get an error saying

API does not accept files of this type

Does anyone have an idea on what the best option is? The only thing I can think of is upload the file to a host like cloudinary, then get the url from that and upload via the url from cloudinary.

Upvotes: 1

Views: 200

Answers (2)

Lea Krause
Lea Krause

Reputation: 432

You are right, a possible solution for your case is using Cloudinary.

Cloudinary's Ruby integration library is available as an open-source Ruby GEM.

To install the Cloudinary Ruby GEM, run:

gem install cloudinary

If you use Rails 3.x or higher, edit your Gemfile, add the following line and run bundle.

gem 'cloudinary'

Your cloud_name account parameter is required to build URLs for your media assets. api_key and api_secret are further needed to perform secure API calls to Cloudinary.

Setting the configuration parameters can be done either programmatically in each call to a Cloudinary method or globally using a cloudinary.yml configuration file, located under the config directory of your Rails project.

Here's an example of a cloudinary.yml file:

production: cloud_name: "sample" api_key: "874837483274837" api_secret: "a676b67565c6767a6767d6767f676fe1"

Uploading directly from the browser is done using Cloudinary's jQuery plugin

http://cloudinary.com/documentation/jquery_integration

To ensure that all uploads were authorized by your application, a secure signature must first be generated in your server-side Rails code.

Full disclosure: I work as a software engineer at Cloudinary.

Upvotes: 2

davidhu
davidhu

Reputation: 10432

A solution I found is the create a duplicate copy of the uploaded files in the public folder and then process from there.

uploaded_file = params["file"]
file_name = uploaded_file.original_filename
file_path = File.expand_path(uploaded_file.tempfile.path)
file = File.open("#{FILE_PATH}/#{file_name}", "wb")

file.write uploaded_file.tempfile.read
file.close

Upvotes: 1

Related Questions