Forum: Ruby Ruby Rails - serving image files

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
47df9891a167136ac0444054edaa31ba?d=identicon&s=25 unknown (Guest)
on 2006-01-09 18:25
(Received via mailing list)
I'm pretty new to Ruby and Rails.  I am writing a Rails application
that is meant to be run on a local machine.  It allows the user to
select a bunch of image (jpg, gif, etc)  files from anywhere on their
file system and add them to an album.

The prototype of the is app is going to leave the images where they are
on the disk (and not persist them anywhere else).  I want to write a
controller that can take an image name and location on disk as a
parameter and then serve the file to the user via the WEBrick server so
that the image appears properly in the browser.

Is there any sample code anywhere for opening a binary file and serving
it as jpg (or whatever) to the user?

Regards
0ea106067aabd24655dedf7b95fce9a6?d=identicon&s=25 Edwin Eedwin (edwin)
on 2006-09-29 23:49
unknown wrote:
> I'm pretty new to Ruby and Rails.  I am writing a Rails application
> that is meant to be run on a local machine.  It allows the user to
> select a bunch of image (jpg, gif, etc)  files from anywhere on their
> file system and add them to an album.
>
> The prototype of the is app is going to leave the images where they are
> on the disk (and not persist them anywhere else).  I want to write a
> controller that can take an image name and location on disk as a
> parameter and then serve the file to the user via the WEBrick server so
> that the image appears properly in the browser.
>
> Is there any sample code anywhere for opening a binary file and serving
> it as jpg (or whatever) to the user?
>
> Regards

I am an experienced programmer but new to Ruby (and Rails), and I had a
similar need to create a Ruby program that would merely serve a jpeg
image. The resulting program is trivial, probably so trivial that I
couldn't find it on the web. The information is in the documentation,
but you really have to connect the dots, not simple for someone new to a
domain. After an embarrassing amount of effort, I came up with the
following program:

#!/usr/bin/env ruby
require 'cgi'

f = File.new("served_image.jaypeg", "r")

cgi = CGI.new

cgi.out( "type"       => "image/jpeg",
          "expires"    => Time.now + 3600 ) { f.read }

(The "expires" item is a purely gratuitious addition.)
This topic is locked and can not be replied to.