使用 Python 上传文件

2023-11-26

我有一个 HTML 表单,并且正在使用 Python 根据输入生成日志文件。我还希望能够允许用户上传图像(如果他们选择)。我可以弄清楚如何使用 Python 来操作它,但我不知道如何上传图像。这肯定是以前做过的,但我很难找到任何例子。你们中有人能指出我正确的方向吗?

基本上,我正在使用cgi.FieldStorage and csv.writer来制作日志。我想从用户的计算机获取图像,然后将其保存到我的服务器上的目录中。然后我将重命名它并将标题附加到 CSV 文件中。

我知道这有很多选择。我只是不知道它们是什么。如果有人可以指导我获取一些资源,我将非常感激。


既然您说您的特定应用程序是与 python cgi 模块一起使用,那么快速谷歌就会找到大量示例。这是第一个:

最小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 日:根据评论,我添加了对此旧活动状态片段的更新:

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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Python 上传文件 的相关文章

随机推荐