【问题标题】:Using Python and the Pillow Library and CGI for file upload使用 Python 和 Pillow 库和 CGI​​ 进行文件上传
【发布时间】:2015-04-27 08:42:02
【问题描述】:

我一直很难同时导入图像和 CGI​​。所以,基本上我想上传一个 gif 图像,然后显示输出,它是图像的缩略图。我收到一堆错误。我无法同时使用 from PIL import 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>")

【问题讨论】:

  • edit 提出您的问题,并附上您收到的任何错误或追溯的全文
  • 我收到此错误:标题前脚本输出结束:save_file.py
  • 我建议将 print ("Content-Type: text/html\n") 放在最顶部;不确定您要托管什么,但至少 apache 对首先看到它非常挑剔。 (此外,您是否在 Windows 上的 /var/log/httpd/error.log 等效项中看到任何内容)。最后...仅最后 6 行将消息设置为 hello world(以排除枕头问题)

标签: python pillow


【解决方案1】:

我想通了。 print html后面一定要有try语句,然后我会用from PIL import Image

【讨论】:

    猜你喜欢
    • 2017-03-09
    • 2015-02-15
    • 2011-06-20
    • 1970-01-01
    • 2013-04-25
    • 1970-01-01
    • 2011-10-18
    • 2013-12-24
    • 1970-01-01
    相关资源
    最近更新 更多