tags:

views:

49

answers:

1

I'm using Pylons to upload an image and store it to disk:

 <form method="post">
 <input type="file" name="picture" enctype="multipart/form-data" />
 </form>

Then in my controller:

 if 'picture' in request.POST:

     i = ImageHandler()

     #Returns full path of image file
     picture_file = i.makePath()

     shutil.copyfileobj(request.POST['picture'],picture_file)

But I receive the error: AttributeError: 'unicode' object has no attribute 'read'

What's going on here? Thanks for your help.

+2  A: 

Both arguments to copyfileobj are now strings, while that functions takes files (or "file-like objects") as arguments. Do something like

 picture_file = open(i.makePath(), 'w')

(or just picture_file = i, not sure what your ImageHandler class is like), then

 shutil.copyfileobj(request.POST['picture'].file, picture_file)
larsmans
Thanks. I still get the same error, though. Could it be a problem with my first argument? Or is request.POST['picture'] correct as is?
ensnare
I just revised my answer.
larsmans
This is so strange, when I do that, I get: AttributeError: 'unicode' object has no attribute 'file'
ensnare
The reason you are having trouble after following larsman's answer is that you are not actually uploading the file. This is because the `enctype` parameter in the HTML goes on the *form*, not the field.
Daniel Roseman
Wow, thanks for the obvious error. Works now!
ensnare