Skip to content

Instantly share code, notes, and snippets.

@maxivak
Created January 1, 2013 23:34
Show Gist options
  • Select an option

  • Save maxivak/4430975 to your computer and use it in GitHub Desktop.

Select an option

Save maxivak/4430975 to your computer and use it in GitHub Desktop.
Rails. Download remote image as attachment in browser
# in controller
# for local files
send_file '/path/to/file', :type => 'image/jpeg', :disposition => 'attachment'
# for remote files
require 'open-uri'
url = 'http://someserver.com/path/../filename.jpg'
data = open(url).read
send_data data, :disposition => 'attachment', :filename=>"photo.jpg"
@Valve

Valve commented Mar 6, 2014

Copy link
Copy Markdown

Excellent, thank you.

@jmwelch

jmwelch commented Feb 5, 2015

Copy link
Copy Markdown

+1. Just to note, if you don't know what type of file you'll be remotely downloading ahead of time, just remove the .jpg extension from :filename!

@daddydanielt

Copy link
Copy Markdown

Thanks, it's very helpful to me.

@YoranBrondsema

Copy link
Copy Markdown

I wouldn't recommend using this with user-specified URL because of security issues with using open-uri. This article sums it up well.

@mikevoets

Copy link
Copy Markdown

I don't think this is a good idea, as you'll be reading all the file data into memory (in data). Depending on the file size, this becomes a problem.

@ramyasrees

Copy link
Copy Markdown

hello sir,how to get perticular url from json?
$.each(files, function(key,value){
alert(value.link)});

in my code how can i store the link value in avariable?

@oshanz

oshanz commented Nov 6, 2019

Copy link
Copy Markdown

if you are going to serve aws s3 files like this, you are gonna loose all the benefits like CDN and high availability features.
because this way you download file to the server. it become a network bottleneck.

@shahroon

Copy link
Copy Markdown

A lot of load on server's memory. Not recommended.

@sebackend

Copy link
Copy Markdown

what about the file after downloading? is it still persist on the server?

i think the file should be removed after the controller response

@vishaljangir

Copy link
Copy Markdown

thank you

@khoan

khoan commented Mar 2, 2021

Copy link
Copy Markdown

shahroon commented on 13 Nov 2019
A lot of load on server's memory. Not recommended.

maybe, pass an enum with some sensible limit?

send_data data.each(512)...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment