简体   繁体   中英

How to handle file upload in python in windows?

I do post a HTML form to a python script running on a simple python server. There are up to 10 files posted within one post request. The image data is accessed like this:

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

The code above works fine on Python 3.2.3 under Mac OS 10.8. I do get random errors under Python 3.2.3 in Win7 . File uploads are not complete randomly. I get the complete file uploaded sometimes, I get a truncated file sometimes.

The HTML form posting the data looks like:

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

Does anyone know why this happens under Win7?

EDIT

The python server executing the script looks like

#!/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()
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

From this page: http://webpython.codepoint.net/cgi_file_upload

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM