使用Python上传文件 [英] Upload a File with Python

查看:182
本文介绍了使用Python上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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.FieldStorage csv.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配方) 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()

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

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.

更新04/12/15 :每条评论,我已添加在这个旧的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)

这篇关于使用Python上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆