既然您说您的特定应用程序是与 python cgi 模块一起使用的,那么快速谷歌就会找到大量示例。这是第一个:
最小 http 上传 cgi (Python recipe) ( snip )
def save_uploaded_file (form_field, upload_dir):
"""This saves a file uploaded by an HTML form.
The form_field is the name of the file input field from the form.
For example, the following form_field would be "file_1":
<input name="file_1" type="file">
The upload_dir is the directory where the file will be written.
If no file was uploaded or if the field does not exist then
this does nothing.
"""
form = cgi.FieldStorage()
if not form.has_key(form_field): return
fileitem = form[form_field]
if not fileitem.file: return
fout = file (os.path.join(upload_dir, fileitem.filename), 'wb')
while 1:
chunk = fileitem.file.read(100000)
if not chunk: break
fout.write (chunk)
fout.close()
此代码将获取文件输入字段,这将是一个类似文件的对象。然后它将逐块读取到输出文件中。
2015 年 4 月 12 日更新:根据评论,我添加了对这个旧的 activestate 片段的更新:
import shutil
def save_uploaded_file (form_field, upload_dir):
form = cgi.FieldStorage()
if not form.has_key(form_field): return
fileitem = form[form_field]
if not fileitem.file: return
outpath = os.path.join(upload_dir, fileitem.filename)
with open(outpath, 'wb') as fout:
shutil.copyfileobj(fileitem.file, fout, 100000)