Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Ruby File Uploads Using PostgreSQL's Large Objects

DZone's Guide to

Ruby File Uploads Using PostgreSQL's Large Objects

·
Free Resource
provided by Robby, with a Rails tutorial coming soon (hopefully).

DB structure:

CREATE DATABASE filedb;
 
\c filedb
 
CREATE TABLE files (
  id SERIAL PRIMARY KEY NOT NULL,
  file_oid OID,
  name TEXT,
  size INT,
  type TEXT,
  created_at TIMESTAMP DEFAULT now()
);
 
COMMENT ON TABLE files IS 'table for storing cool files'

ruby code: 
#!/usr/bin/env ruby
 
file = ARGV[0]
 
require "postgres"
require "readbytes"
 
READ_SIZE = 8192
 
conn = PGconn.connect("localhost", 5432, "","", "filedb", "user", "pass")
 
conn.exec("BEGIN")
lo = conn.lo_import(file)
conn.exec("COMMIT")
 
### error checking before you get here
### quick and ugly sql!
size = File.stat(file).size
sql = "INSERT INTO files (file_oid, name, size, type) VALUES (#{lo.oid},'#{file}','#{size}','image/jpeg');"
conn.exec(sql)
 
puts "large object id: #{lo.oid}"
 
--------------------
 
$ ./lo_import.rb 6.jpg
large object id: 323476
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}