gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:51:22 25 4
gpt4 key购买 nike

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

最佳答案

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

关于python - 如何在 Windows 中用 python 处理文件上传?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12625379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com