Search code examples
pythonimagepyramiduploading

Pyramid - uploading images and storing on disk


I'm trying to implement a system of uploading a file (image) to the server running pyramid. Right now, this code gives me an AttributeError: 'unicode' object has no attribute 'file' exception:

Server-side:

session = Session()
username = authenticated_userid(request)
if username == None:
    return HTTPNotFound()
else:
    user = session.query(User).filter(User.username == username).first()
if 'photo.submitted' in request.params:
    input_file = request.POST['file_input'].file
    tmp = '../static/images/%s' % (session.query(ProfilePic).order_by(-ProfilePic.photo_id).first().photo_id + 1)
    open(tmp, 'w').write(input_file.read())
    tmp.close()
    return Response('OK')
return {}

HTML:

<html>
<body>
    <form action="/settings" method="post">
        <input type="file" name="file_input" value="Choose image" />


    <p><input type="submit" name="photo.submitted" value="Save" /></p>
    </form>
</body>
</html>

Something that seems simple, but won't work. I was trying to follow this tutorial, but it seems it only works with video/audio files. How could I make this work?


Solution

  • For file uploads, you need to alter the form enctype to use multipart/form-data:

    <html>
    <body>
        <form action="/settings" method="post" enctype="multipart/form-data">
            <input type="file" name="file_input" value="Choose image" />
    
    
        <p><input type="submit" name="photo.submitted" value="Save" /></p>
        </form>
    </body>
    </html>