【问题标题】:How to do an image upload in web.py and save it to the disk如何在 web.py 中上传图片并将其保存到磁盘
【发布时间】:2011-07-25 04:51:07
【问题描述】:

我需要创建一个表单并让表单上传图像并将其保存到我的磁盘。这是我的代码

import web

urls = (
'/hello', 'Index',
'/file_upload_form', 'ThatFile'
)

app = web.application(urls, globals())

render = web.template.render('templates/', base = "layout")

class ThatFile(object):
    def GET(self):
        return render.file_upload_form()

    def POST(self):
        form = web.input(image = "loc")
        open(form.image,'r')
        image_o = form.image.read()
        return render.thatfile(o_image = o_image)

class Index(object):
    def GET(self):
        return render.hello_form()

    def POST(self):
        form = web.input(name = "Nobody", greet = None)
        greeting = "%s, %s" % (form.greet, form.name)
        return render.index(greeting = greeting)

if __name__ == "__main__":
    app.run()

我尝试过使用 PIL Image 模块,但它不显示图像。

【问题讨论】:

  • 代码中的位置是什么,您认为将文件保存到磁盘的位置是什么?我找不到它。而且文件不会神奇地自我保存。
  • 我知道我不确定如何将文件保存到磁盘。我现在可以打开文件并在新页面中打印,但无法保存。所以代码的保存部分不在里面。

标签: python upload web.py


【解决方案1】:

使用类似的东西

import shutil
# SKIPPED
def POST(self):
    form = web.input(image={})
    with open('path/to/image.jpg', 'wb') as saved:
        shutil.copyfileobj(form['image'].file, saved)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-26
    • 2011-01-25
    • 1970-01-01
    • 2021-02-27
    • 2021-07-01
    • 1970-01-01
    相关资源
    最近更新 更多