使用web.py和Python以HTML格式进行文件上载字段验证

时间:2014-11-30 19:03:15

标签: python web.py

我正在使用Python 2.7和web.py构建一个网站,允许用户上传图片文件,指定文件位置/文件名,然后将图片文件保存到该位置/名称。

我想验证2件事情并通过错误消息,以防验证没有检出: 1.验证表单上已选择的文件 2.验证文件位置文本框是否已填充

我对2没有问题。但是,对表单上的文件上传控件的验证不起作用。它始终认为没有选择任何文件,因此即使正确选择了文件,也会返回错误。

我在下面为我的app.py和包含该表单的index.html附加了我的代码。任何指针都非常感谢!

app.py

import web
import shutil

# The (.*) along with the name parameter in the def GET method line
# allows to enter parameter into web address without the
# ?parameter=xxx syntax.

#urls = (
#    "/(.*)", "Index")

urls = (
    "/", "Index")

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


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


class Index(object):

 #   def GET(self, name):
  #      return render.index(name)

    def GET(self):
        return render.index()


    def POST(self):

        form = web.input(myimage={}, fileloc=None)

# The following line validates whether the fileloc text box has been populated.
# I don't know how to also validate that the file upload field has been populated!
# The value for the control always shows as empty, even if a file has been selected!
# Currently, if the file control is empty, the program will run but save an empty file.        

        if form.fileloc and form.myimage:

            with open(form["fileloc"], "wb") as saved:
                shutil.copyfileobj(form["myimage"].file, saved)

        else:
            #return render.error()
            return "You must populate the file location and upload a file"

        return render.index()


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

的index.html

<form action="/" method="POST" enctype="multipart/form-data">
    Select the file to be uploaded: <input type="file" name="myimage"><br><br>
    Enter full path and filename to save the file:    <input type="text" name="fileloc"
        size=75 value="/users/cdignam/desktop/picture.jpg"
        STYLE="background-color: yellow"><br><br>
    <input type="submit" value="Upload">
</form>

1 个答案:

答案 0 :(得分:0)

尝试替换

f form.fileloc and form.myimage:

if form.fileloc and form["myimage"].filename: