使用Python上传文件

使用Python上传文件,第1张

使用Python上传文件

既然您说过您的特定应用程序是与python cgi模块一起使用的,那么快速的Google会举很多例子。这是第一个:

最小的http上传cgi(Python配方)( 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 shutildef 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)


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5664563.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存