linkhyrule5
linkhyrule5

Reputation: 918

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.

Upvotes: 3

Views: 4130

Answers (2)

podenborg
podenborg

Reputation: 88

I tried the methods above but it kept automatically downloading the files to disk, which wasn't what I wanted.

To get the file to be opened, and viewed, in the browser I had to move the file to the public/ folder and then it will be accessible by going to myappdomain.com/filename.pdf

Upvotes: 0

MarsAtomic
MarsAtomic

Reputation: 10673

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.

Upvotes: 6

Related Questions