Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest Way to Serve Files - Ruby on Rails

What's the simplest way to serve files in Rails?

By this I mean: I'd like to go to, say, http://myserver.com/assets/arbitraryfile.arbitraryformat and have it just load arbitraryfile.arbitraryformat in the browser, letting the browser decide whether to download it or display it or whatever else. (In particular I plan to make a bookmarklet that invokes a *.js file from the server, which in turn loads a *.css file and downloads a font *.tty file from the same.)

Currently I've got an assets resources routing to an assets#show action, but I'm not at all sure how to code my show.

like image 738
linkhyrule5 Avatar asked Sep 17 '25 10:09

linkhyrule5


1 Answers

You'd stream the data to the browser and let it do whatever it needs to do. You can use one of two rails methods to get what you want:

a) send_data

foo_data = "This is my data"
send_data(foo_data, filename: "foo_file.txt")

b) send_file (which allows you to use a path)

send_file("my_app/assets/public/pdf/my_pdf.pdf", type: "application/pdf")

Check out the official doc.

like image 144
MarsAtomic Avatar answered Sep 19 '25 04:09

MarsAtomic