我是Tornado的新手并尝试制作一个简单的多文件上传表单,以便用户能够上传一个或多个文件。
以下是upload.py
中的相关部分class UploadHandler(tornado.web.RequestHandler):
def get(self):
files_dict = {}
self.render("upload_form.html", files_dict = files_dict)
def post(self):
ofn="" #original file name
ufn="" #uploaded file name
files_dict = {} # dict of original:uploaded names
#file1
if self.request.files['file1'][0]:
file1 = self.request.files['file1'][0] #infput file
ofn = file1['filename']
extension = os.path.splitext(ofn)[1]
if extension in EXT:
fname = ''.join(random.choice(string.ascii_lowercase + string.digits) for x in range(8))
ufn= fname+extension
output_file = open("uploads/" + ufn, 'w')
output_file.write(file1['body'])
files_dict[ofn]= ufn
else:
files_dict[ofn]= None
#file2
if self.request.files['file2'][0]:
file2 = self.request.files['file2'][0] #infput file
ofn = file2['filename']
extension = os.path.splitext(ofn)[1]
if extension in EXT:
fname = ''.join(random.choice(string.ascii_lowercase + string.digits) for x in range(8))
ufn= fname+extension
output_file = open("uploads/" + ufn, 'w')
output_file.write(file1['body'])
files_dict[ofn]= ufn
else:
files_dict[ofn]= None
self.render("upload_form.html", files_dict= files_dict )
upload_form.html中的表单:
<form enctype="multipart/form-data" action="/upload" method="post" class="center" >
File1 <input type="file" name="file1" /> <br />
File2 <input type="file" name="file2" /> <br />
<input type="submit" value="upload" class="button" />
</form>
当发布File1和File2时,这样可以正常工作但当其中任何一个为空时,我会收到如下错误:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/tornado-3.1.1-py2.7.egg/tornado/web.py", line 1141, in _when_complete
callback()
File "/usr/local/lib/python2.7/dist-packages/tornado-3.1.1-py2.7.egg/tornado/web.py", line 1162, in _execute_method
self._when_complete(method(*self.path_args, **self.path_kwargs),
File "upload.py", line 41, in post
if self.request.files['file2'][0]:
KeyError: 'file2'
我尝试了不同的技巧,比如将每个文件上传代码放在一个try中,除了块或添加额外的条件以检查File的主体是否存在但是都是徒劳的。非常感谢您的提示。
答案 0 :(得分:2)
您有KeyKerror
因为字典中没有这样的密钥。请尝试以下代码:
test_dict = {"a":"a"}
if test_dict['a']:
print "test_dict[a] - ok"
if test_dict['b']:
print "test_dict[b] - ok"
输出:
test_dict[a] - ok
Traceback (most recent call last):
File "test.py", line 6, in <module>
if test_dict['b']:
KeyError: 'b'
使用in
来测试您是否在字典中输入了密钥:
def post(self):
ofn="" #original file name
ufn="" #uploaded file name
files_dict = {} # dict of original:uploaded names
#file1
if 'file1' in self.request.files:
file1 = self.request.files['file1'][0] #infput file
# ...
#file2
if 'file2' in self.request.files:
file2 = self.request.files['file2'][0] #infput file
# ...
# ...