我确实将 HTML 表单发布到在简单的 python 服务器上运行的 python 脚本。一个帖子请求中最多可以发布 10 个文件。图像数据的访问方式如下:
import cgi
# simple post data access
form = cgi.FieldStorage()
imgfieldname = "image1"
imagedata = form[imgfieldname].file.read()
# size varies for the same source image file for different uploads
# on Win7 for no obvious reason
size = len(imagedata)
# save image data to file, results in an truncated image on Win7
# as the image is already truncated when read from form above
fh = open("image1", "wb")
fh.write(imagedata)
fh.close()
上面的代码在 Mac OS 10.8 下的 Python 3.2.3 上运行良好。我确实在 Win7 中的 Python 3.2.3 下遇到随机错误。文件上传不是随机完成的。我有时会上传完整的文件,有时会收到截断的文件。
发布数据的 HTML 表单如下所示:
<form action="/cgi-bin/save.py" method="post" name="Formular" id="Formular" enctype="multipart/form-data">
<input type="file" formenctype="multipart/form-data" name="image1"/>
<input type="file" formenctype="multipart/form-data" name="image2"/>
<input type="file" formenctype="multipart/form-data" name="image3"/>
<input type="file" formenctype="multipart/form-data" name="image4"/>
<input type="file" formenctype="multipart/form-data" name="image5"/>
<input type="submit" value="save" />
</form>
有谁知道为什么在Win7下会发生这种情况?
编辑
执行脚本的 python 服务器看起来像
#!/usr/bin/env python
#-*- coding: ISO-8859-1 -*-
import http.server
import socketserver
import subprocess
import os
import time
import threading
import cgi
import cgitb; cgitb.enable()
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
PORT = 8000
class MyHandler(http.server.CGIHTTPRequestHandler):
# Disable logging DNS lookups
def address_string(self):
return str(self.client_address[0])
class ThreadingHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
pass
if __name__=='__main__':
#Handler = http.server.CGIHTTPRequestHandler
Handler = MyHandler
#httpd = http.server.HTTPServer(("", PORT), Handler)
httpd = ThreadingHTTPServer(('localhost', 8000), Handler)
print("serving at port", PORT)
httpd.serve_forever()