使用 Python 上传文件

2022-01-09 00:00:00 python image cgi upload

问题描述

我有一个 HTML 表单,我正在使用 Python 根据输入生成一个日志文件.如果用户愿意,我还希望能够允许用户上传图片.一旦它在那里,我可以弄清楚如何用 Python 操作它,但我不确定如何上传图像.这肯定是以前做过的,但我很难找到任何例子.你们谁能指出我正确的方向吗?

I have an HTML form and I am using Python to generate a log file based on the input. I'd like to also be able to allow the user to upload an image if they choose. I can figure out how to manipulate it with Python once it's there, but I'm not sure how to get the image uploaded. This has most certainly been done before, but I'm having a hard time finding any examples. Can any of you point me in the right direction?

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

Basically, I'm using cgi.FieldStorage and csv.writer to make the log. I want to get an image from the user's computer and then save it to a directory on my server. I will then rename it and append the title to the CSV file.

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

I know there are a lot of options for this. I just don't know what they are. If anyone could direct me toward some resources I would be very appreciative.


解决方案

既然你说你的特定应用程序是与 python cgi 模块一起使用的,那么快速谷歌就会找到很多例子.这是第一个:

Since you said that your specific application is for use with the python cgi module, a quick google turns up plenty of examples. Here is the first one:

最小 http 上传 cgi(Python 配方) (剪辑)

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()

此代码将获取文件输入字段,该字段将是一个类似文件的对象.然后它将逐块读取到输出文件中.

This code will grab the file input field, which will be a file-like object. Then it will read it, chunk by chunk, into an output file.

2015 年 4 月 12 日更新:根据评论,我添加了对这个旧的 activestate 片段的更新:

Update 04/12/15: Per comments, I have added in the updates to this old activestate snippet:

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)

相关文章