Last active
February 2, 2016 12:32
-
-
Save mjquinlan2000/10929611 to your computer and use it in GitHub Desktop.
Proxy multipart/form-data requests through Rails controller to foreign API using Faraday and Dropzone
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Somewhere in your client code after dropzone.js has been included | |
//... | |
var myZone = new Dropzone('.selector', { | |
url: '/my/upload/path?parameters=true', | |
sending: function(file, xhr, formData) { | |
// Do some custom data transformation before file submission... blah blah blah | |
}, | |
success: function(file, response) { | |
// Do something with the file or response here! | |
}, | |
error: function(file, error) { | |
// Handle the error accordingly | |
} | |
}); | |
//... |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Make sure to add this to your Gemfile | |
gem 'faraday' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyUploadController < ApplicationController | |
def file_upload | |
# Parse file data into an UploadIO object... | |
payload = {} | |
payload[:file] = Faraday::UploadIO.new params[:file].path, params[:file].content_type | |
connection = Faraday.new 'http://some.foreign.api' do |faraday| | |
faraday.request :multipart | |
faraday.headers['Content-Type'] = 'multipart/form-data' | |
faraday.adapter Faraday.default_adapter | |
# Any other faraday logic here... | |
end | |
# Optionally use a put request if you so desire | |
response = connection.post '/path/to/resource', payload | |
render json: response.body, status: response.status | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment