我是 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'
我尝试了不同的技巧,例如将每个文件上传代码放在一个尝试中,除了块或添加额外的条件来检查文件的主体是否存在但一切都是徒劳的。所以感谢你的提示。