ruby file uploads using PostgreSQL's Large Objects
DB structure:
1 CREATE DATABASE filedb; 2 3 \c filedb 4 5 CREATE TABLE files ( 6 id SERIAL PRIMARY KEY NOT NULL, 7 file_oid OID, 8 name TEXT, 9 size INT, 10 type TEXT, 11 created_at TIMESTAMP DEFAULT now() 12 ); 13 14 COMMENT ON TABLE files IS 'table for storing cool files'
ruby code:
1 #!/usr/bin/env ruby 2 3 file = ARGV[0] 4 5 require "postgres" 6 require "readbytes" 7 8 READ_SIZE = 8192 9 10 conn = PGconn.connect("localhost", 5432, "","", "filedb", "user", "pass") 11 12 conn.exec("BEGIN") 13 lo = conn.lo_import(file) 14 conn.exec("COMMIT") 15 16 ### error checking before you get here 17 ### quick and ugly sql! 18 size = File.stat(file).size 19 sql = "INSERT INTO files (file_oid, name, size, type) VALUES (#{lo.oid},'#{file}','#{size}','image/jpeg');" 20 conn.exec(sql) 21 22 puts "large object id: #{lo.oid}" 23 24 -------------------- 25 26 $ ./lo_import.rb 6.jpg 27 large object id: 323476