Image upload using CGI Python - Doesn’t work!

Asked

Viewed 247 times

0

Hello, I created an html file with one and I intend to select an image from a directory and after clicking on Ubmit this image should be saved in another directory. Some help?

That’s what I’ve tried so far...

index.html

<form name="pyform" method="POST" action="upload.py"> 
   <input type="file" name="image" /><br />
   <input type="submit" name="submit" value="Submit" />
</form>

upload.py

#!c:/Python34/python
# -*- coding: UTF-8 -*-
print("Content-Type: text/html")
print()

import cgi,cgitb
cgitb.enable()

form = cgi.FieldStorage()
file = form['image'].value

upload_dir = 'C:/wamp/www/upload/' # esse é o diretório onde vou salvar a imagem

f = open(upload_dir + file, 'w')
f.write(file)
f.close()

I noticed that after executing the code, a file with the same name as the image is created, however, with size 0kb and cannot be displayed.

  • you Managed to miss two Different simple Steps, and have each of These Steps directed in one of the two Answers Bellow.

2 answers

1


You must open, read and write the file in binary mode this way:

f = open(file, mode = 'rb') #'rb' para ler arquivos binários 
f2 = open(upload_dir + file, 'wb')  #'wb' para gravar arquivos binários
f2.write(f.read())

Or you can do it like this:

with open(file, mode='rb') as f:
    with open(upload_dir+file, mode='wb') as f2:
        f2.write(f.read())

so resources are automatically closed.

  • Actually, there are two problems - one is access to the file data - the other is in the HTML form, whose tag <form> should Cotner the attribute enctype="multipart/form-data" as in @Wallace’s reply

  • The use of with so it’s a bit Overkill too - but if it’s done, for quite some time it’s possible to have more than one object with context management in the same command with, separated by comma - there’s no need to nestle two with

1

Well, I think your problem is simpler to solve.

Your form must contain the attribute enctype="multipart/form-data".

I guess you forgot.

  • actually, two things are missing - one is this, the other is that the file upload field does not have a "value" attribute - but a "file" attribute that should be read as in the @Ironman reply

Browser other questions tagged

You are not signed in. Login or sign up in order to post.