I'm using Python 2.7 and web.py to build a website that allows user to upload a picture file, specify a file location / file name, then save the picture file to that location / name.
I want to validate 2 things and through up an error message in case the validation does not check out: 1. validate a file has been selected on the form 2. validate the file location text box has been populated
I have no problem with 2. However, validation of the file upload control on the form does not work. It always thinks that no file has been selected, so returns the error, even when a file has been correctly selected.
I'm attaching my code below for my app.py and the index.html that contains the form. Any pointers greatly appreciated!
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>
Try replacing
f form.fileloc and form.myimage:
with
if form.fileloc and form["myimage"].filename: