使用Python和Pillow Library和CGI进行文件上传

时间:2015-04-26 23:27:21

标签: python pillow

我一直很难将Image和CGI一起导入。所以,基本上我想上传一个gif图像,然后显示输出,这是图像的缩略图。我收到一堆错误。我无法同时使用PIL导入Pillow和cgi。这是下面的代码。非常感谢您的帮助。我做了几个小时的研究,无法弄清楚。我收到此错误:标题之前的脚本输出结束:save_file.py

#!C:\Anaconda3\python.exe
from PIL import Image
import cgi, os
import cgitb; cgitb.enable() #cgitb enabled for bug tracking purposes
try: # Windows needs stdio set for binary mode. 
    import msvcrt
    msvcrt.setmode (0, os.O_BINARY) # stdin  = 0
    msvcrt.setmode (1, os.O_BINARY) # stdout = 1
except ImportError:
    pass

form = cgi.FieldStorage()

# A nested FieldStorage instance holds the file
fileitem = form['file']


# Test if the file was uploaded
if fileitem.filename:

   # strip leading path from file name to avoid directory traversal attacks
   fn = os.path.basename(fileitem.filename)
   ext = fn[-3:]
   condi = 'gif'
   if ext == condi:
    open('tmpmedia/' + fn, 'wb').write(fileitem.file.read())
    message = 'The file "' + fn + '" was uploaded successfully'
    selectfunction = "Please select a function from below"
   else:
    message = 'You can only upload a gif image. No file was uploaded'
size = (128,128)
saved = "thumb.jpg"
infile = ('C:\\xampp\\htdocs\\aztec\\tmpmedia\\gif' + fn)
try:
    im = Image.open(infile)
except:
    print("Unable to load image")
im.thumbnail(size)
im.save(saved)
print ("Content-Type: text/html\n")
print ("<html>")
print("<body>")
print(message)
print("</body>")
print("</html>")

1 个答案:

答案 0 :(得分:0)

我明白了。在打印html之后必须有一个try语句,然后我将使用PIL import Image