#!/usr/bin/python

"An HTML form to upload a picture, and process the uploaded object too"

import cgi
import sqlite3
import os.path

def guess_mimetype(ext):
    if ext in ('.jpg','.jpeg'): return 'image/jpeg'
    if ext == '.png': return 'image/png'
    if ext == '.bmp': return 'image/bmp'
    return 'application/octet-stream'
    
form = cgi.FieldStorage()

if form.has_key("upload"):
    # the user has uploaded a picture
    title = form['title'].value
    description = form['description'].value
    picture = form['picture'].value
    ext = os.path.splitext(form['picture'].filename)[1]
    mimetype = guess_mimetype(ext)
    conn = sqlite3.connect("demo.db")
    cursor = conn.cursor()
    # fake autoincrement - unsafe!
    cursor.execute("select max(id) from album")
    picid = int(cursor.fetchone()[0] or 0)+1
    sql = ("insert into album "
           "(id, title, description, picture, mimetype) values "
           "(?,?,?,?,?)")
    cursor.execute(sql, (
        picid, title, description, sqlite3.Binary(picture), mimetype))
    conn.commit()
    conn.close()
    print "Content-Type: text/html"
    print
    print "<html><head><title>Upload OK</title></head>" 
    print "<body>"
    print "<h1>Upload OK</h1>" 
    print "<p>Title: %s</p>" % cgi.escape(title)
    print "<p>Description: %s</p>" % cgi.escape(description)
    print "<p>Size: %s</p>" % len(picture)
    print "<p>Back to <a href='album.py'>album</a></p>"
    print "</body></html>"

else:
    # show form to upload pictures
    print "Content-Type: text/html"
    print
    print "<html><head><title>Upload new picture</title></head>" 
    print "<body>"
    print "<h1>Upload new picture</h1>" 
    print "<form method=post action='upload.py' enctype='multipart/form-data'>" 
    print "<table>"
    print "<tr><th>Title</th><td><input name=title size=30 type=text></td></tr>" 
    print "<tr><th>Description</th><td><input name=description size=30 type=text></td></tr>" 
    print "<tr><th>Picture</th><td><input name=picture type=file></td></tr>" 
    print "<tr><td colspan=2>"
    print "<input type=submit name=upload value=Upload>"
    print "</td></tr>" 
    print "</table></form>"
    print "<p>Back to <a href='album.py'>album</a></p>"
    print "</body></html>"
