Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Download remote file with Paperclip gem
# Scenario 1: remote resource returns a binary file;
# the last part of the uri represents the file name
# e.g. http://someurl.com/artists/jeanlucponty/tracks/elephants-in-love.mp3
class Audio < ActiveRecord::Base
has_attached_file :file
def file_from_url(url)
self.file = download_remote_file(url)
end
private
def download_remote_file(url)
# OpenURI extends Kernel.open to handle URLs as files
io = open(url)
# overrides Paperclip::Upfile#original_filename;
# we are creating a singleton method on specific object ('io')
def io.original_filename
base_uri.path.split('/').last
end
io.original_filename.blank? ? nil : io
end
end
# Scenario 2: remote resource returns a binary file in the response body;
# along with the filename in the response headers, e.g.
# Content-Type: audio/mp3
# Content-Transfer-Encoding: binary
# Content-Disposition: attachment; filename=chopping_broccoli.mp3"
class Audio < ActiveRecord::Base
has_attached_file :file
def file_from_url(url)
self.file = download_remote_file(url)
end
private
def download_remote_file(url)
# OpenURI extends Kernel.open to handle URLs as files
io = open(url)
# overrides Paperclip::Upfile#original_filename;
# we are creating a singleton method on specific object ('io')
def io.original_filename
# OpenURI::Meta's meta attribute returns a hash of headers
meta["content-disposition"].match(/filename=(.+[^;])/)[1]
end
io.original_filename.blank? ? nil : io
end
end
# example usage
audio = Audio.new
audio.content_from_url('http://someurl.com/someresource.mp3')
artist.audios << audio
@adamniedzielski

This was extremely helpful! Thanks

@breim

+1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.