栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用Python上传文件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用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)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/662610.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号