Hi,
Thanks for the tips and i've been trying different approaches all day and
reading lots of docs with varying success. Now i can get my file and all but
i still cant get it into the database. Here follows the code and the trace,
the code is not pretty yet but i just wanted it to work since i need to get
finished with this, this has held me up since Sunday.

Thank you for your help,
Fabian

============================================================================
=======
CODE
============================================================================
=======

    def upload_handler(self, imageObject, image1, image2, image3, image4,
image5, **kw):
        """ Do something with form values and re-show the upload form. """

        # Tell UploadFilter that this transfer is done.
        try:
            del
cherrypy.file_transfers[cherrypy.request.remote_addr][image1.filename]
            del
cherrypy.file_transfers[cherrypy.request.remote_addr][image2.filename]
            del
cherrypy.file_transfers[cherrypy.request.remote_addr][image3.filename]
            del
cherrypy.file_transfers[cherrypy.request.remote_addr][image4.filename]
            del
cherrypy.file_transfers[cherrypy.request.remote_addr][image5.filename]
        except KeyError:
            pass

        # Save any files that were uploaded (ignoring empty form fields)
        tmpdir = os.path.join(os.getcwd(), "tempfiles")
        if len(image1.filename) > 0:
            img = image1.file
            img.seek(0)
            chunk_size = 8192
            tmpdir = os.path.join(os.getcwd(), "tempfiles")        
            newFile = open(os.path.join(tmpdir, image1.filename), "wb")
            # save data to this new file in chunks
            while True:
                data = img.read(chunk_size)
                if not data:
                    break
                newFile.write(data)
            self.pre_process_image(os.path.join(tmpdir, image1.filename),
imageObject)
        if len(image2.filename) > 0:
            pass
        if len(image3.filename) > 0:
            pass
        if len(image4.filename) > 0:
            pass
        if len(image5.filename) > 0:
            pass

        # Re-show the upload form, with a nice little message
        flash("The files were uploaded.")
        raise redirect('/modify/images/'+imageObject)
    
    def pre_process_image(self, savedfile, imageObject):
        if self.is_valid_image(savedfile):
            # create file entry in database
            newImage = image(imageName = None,
                             imageDescription = None,
                             imagePoints = None,
                             imageComplete = False,
                             imageMap = False,
                             imageMapPoint = False,
                             imageFile = open(savedfile),
                             imageThumb = None,
#open(self.make_thumbnail(savedfile)),
                             imageObject = int(imageObject),
                             imageSpace = None,
                             imageFormat = 1)
            return
        else:
            return False

    def is_valid_image(self, savedfile):
        try:
            im = Image.open(savedfile)
        except:
            return False
        return True

    def make_thumbnail(self, savedfile):
        pass

============================================================================
=======
TRACE
============================================================================
=======

Page handler: <function _wrapper at 0xb717180c>
Traceback (most recent call last):
  File
"/usr/lib/python2.4/site-packages/CherryPy-2.2.1-py2.4.egg/cherrypy/_cphttpt
ools.py", line 105, in _run
    self.main()
  File
"/usr/lib/python2.4/site-packages/CherryPy-2.2.1-py2.4.egg/cherrypy/_cphttpt
ools.py", line 254, in main
    body = page_handler(*virtual_path, **self.params)
  File
"/usr/lib/python2.4/site-packages/TurboGears-1.0.1-py2.4.egg/turbogears/iden
tity/conditions.py", line 275, in _wrapper
    return fn( *args, **kw )
  File "<string>", line 3, in upload_handler
  File
"/usr/lib/python2.4/site-packages/TurboGears-1.0.1-py2.4.egg/turbogears/cont
rollers.py", line 334, in expose
    output = database.run_with_transaction(
  File "<string>", line 5, in run_with_transaction
  File
"/usr/lib/python2.4/site-packages/TurboGears-1.0.1-py2.4.egg/turbogears/data
base.py", line 302, in so_rwt
    retval = func(*args, **kw)
  File "<string>", line 5, in _expose
  File
"/usr/lib/python2.4/site-packages/TurboGears-1.0.1-py2.4.egg/turbogears/cont
rollers.py", line 351, in <lambda>
    mapping, fragment, args, kw)))
  File
"/usr/lib/python2.4/site-packages/TurboGears-1.0.1-py2.4.egg/turbogears/cont
rollers.py", line 378, in _execute_func
    output = errorhandling.try_call(func, *args, **kw)
  File
"/usr/lib/python2.4/site-packages/TurboGears-1.0.1-py2.4.egg/turbogears/erro
rhandling.py", line 73, in try_call
    return func(self, *args, **kw)
  File
"/files/projects/3001_IC/dev/fabian/workingCopy/test_app/subcontrollers/imag
es.py", line 108, in upload_handler
    self.pre_process_image(os.path.join(tmpdir, image1.filename),
imageObject)
  File
"/files/projects/3001_IC/dev/fabian/workingCopy/test_app/subcontrollers/imag
es.py", line 149, in pre_process_image
    imageFormat = 1)
  File
"/usr/lib/python2.4/site-packages/SQLObject-0.7.2-py2.4.egg/sqlobject/declar
ative.py", line 93, in _wrapper
    return fn(self, *args, **kwargs)
  File
"/usr/lib/python2.4/site-packages/SQLObject-0.7.2-py2.4.egg/sqlobject/main.p
y", line 1203, in __init__
    self._create(id, **kw)
  File
"/usr/lib/python2.4/site-packages/SQLObject-0.7.2-py2.4.egg/sqlobject/main.p
y", line 1227, in _create
    self.set(**kw)
  File
"/usr/lib/python2.4/site-packages/SQLObject-0.7.2-py2.4.egg/sqlobject/main.p
y", line 1086, in set
    kw[name] = dbValue = from_python(value, self._SO_validatorState)
  File
"/usr/lib/python2.4/site-packages/FormEncode-0.6-py2.4.egg/formencode/api.py
", line 356, in from_python
    value = self._from_python(value, state)
  File
"/usr/lib/python2.4/site-packages/FormEncode-0.6-py2.4.egg/formencode/compou
nd.py", line 61, in _from_python
    from_python)
  File
"/usr/lib/python2.4/site-packages/FormEncode-0.6-py2.4.egg/formencode/compou
nd.py", line 118, in attempt_convert
    value = validate(validator, value, state)
  File
"/usr/lib/python2.4/site-packages/FormEncode-0.6-py2.4.egg/formencode/compou
nd.py", line 18, in from_python
    return validator.from_python(value, state)
  File
"/usr/lib/python2.4/site-packages/SQLObject-0.7.2-py2.4.egg/sqlobject/col.py
", line 1229, in from_python
    binary = state.soObject._connection.createBinary(value)
  File
"/usr/lib/python2.4/site-packages/SQLObject-0.7.2-py2.4.egg/sqlobject/dbconn
ection.py", line 558, in createBinary
    return self.module.Binary(value)
  File "/usr/lib/python2.4/site-packages/MySQLdb/__init__.py", line 61, in
Binary
    return array('c', x)
TypeError: array item must be char


-----Original Message-----
From: [email protected] [mailto:[EMAIL PROTECTED] On
Behalf Of Michael Robellard
Sent: 07 February 2007 21:16
To: TurboGears
Subject: [TurboGears] Re: Getting images into and out of a database...been
banging my head against a wall for two days now


First of all Your form needs to have its enctype="multipart/form-data"

In your function for page in your controller you'll have a paramter with the
same name as the name of the file input tag on your form.
That parameter is an object with .file and .filename

You could have something like this in your code def upload(self, file=None)
fd = open(file.filename, 'w') shutil.copyfileobj(file.file, fd)
fd.close()

The .file object is a standard Python file like object and can be used like
that

On Feb 7, 12:18 pm, "Fabian" <[EMAIL PROTECTED]> wrote:
> Hello,
> I've had nothing but problems getting this to work so i'll just 
> describe what i want to do and maybe someone here could help me out:
>
> 1) Get images uploaded via the method describe in the upload with 
> progressbar tutorial in the rough-docs
> 2) write image into a StringIO or similar
> 3) write a copy into the database
> 4) make a thumbnail via PIL
> 5) save thumbnail into database
>
> Now so far i've been getting nothing but errors so i think i've been 
> on the wrong track. Could someone just quickly list what objects to 
> use in this process is StringIO the way to go? The code is here below.
> imageObject is just an Int. I've been getting decoding errors about 
> character not being in ascii range which i assume is because it tries 
> to decode the stringIO object, how do i tell it that it contains 
> binary data?
>
> Thanks a lot
> Fabian
>
>     def save_file(self, filepath, file, imageObject):
>         """ Safely save a file to the location given by filepath """
>         chunk_size = 8192
>         # return if file is empty
>         if not file:
>             return
>         #read file that is being uploaded into a memory file
>         # create new file on file system
>         savedfile = StringIO.StringIO()
>         # save data to this new file in chunks
>         while True:
>             data = file.read(chunk_size)
>             if not data:
>                 break
>             savedfile.write(data)
>
>         savedfile.seek(0)
>
>         #create thumbnail
>         tempThumb = Image.open(savedfile)
>         tempThumb = tempThumb.resize((128, 128))
>         fileOut = StringIO.StringIO()
>         fileOut.seek(0)
>         savedfile.seek(0)
>         tempThumb.save(fileOut, 'PNG')
>
>         # create file entry in database
>         newImage = image(imageName = None,
>                          imageDescription = None,
>                          imagePoints = None,
>                          imageComplete = False,
>                          imageMap = False,
>                          imageMapPoint = False,
>                          imageFile = savedfile.getvalue(),
>                          imageThumb = None,
>                          imageObject = int(imageObject),
>                          imageSpace = None,
>                          imageFormat = 1)
>         return





--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"TurboGears" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/turbogears?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to