如何在Windows中的python中处理文件上传?

时间:2012-09-27 15:55:50

标签: python python-3.x cgi

我将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()

1 个答案:

答案 0 :(得分:1)

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

从此页面:http://webpython.codepoint.net/cgi_file_upload