Image upload using CGI Python - It does not work!

0

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

This is 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 running the code, a file with the same image name is created, however, with size 0kb and can not be displayed.

    
asked by anonymous 29.04.2016 / 21:46

2 answers

1

You should open, read, and write the file in binary mode like this:

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 this:

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

so the features are closed automatically.

    
30.04.2016 / 16:57
1

Well, I think your problem is simpler to solve.

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

I think you forgot.

    
01.05.2016 / 02:31