Tornado为什么无法上传文件?

2012-12-06 11:39:53 +08:00
 kenneth
高手帮忙看下原因?
class UploadHandler(tornado.web.RequestHandler):
def post(self):
file1 = self.request.files['file1'][0]
original_fname = file1['filename']
extension = os.path.splitext(original_fname)[1]
fname = ''.join(random.choice(string.ascii_lowercase + string.digits) for x in range(6))
final_filename= fname+extension
output_file = open("uploads/" + final_filename, 'w')
output_file.write(file1['body'])
self.finish("file" + final_filename + " is uploaded")


Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/tornado-2.4.post1-py2.7.egg/tornado/web.py", line 1064, in _execute
getattr(self, self.request.method.lower())(*args, **kwargs)
File "run.py", line 137, in post
file1 = self.request.files['file1'][0]
KeyError: 'file1'
4070 次点击
所在节点    Tornado
10 条回复
Livid
2012-12-06 11:44:00 +08:00
你的提交页面的 HTML 发上来看看。
binux
2012-12-06 11:44:04 +08:00
上传表单是怎么样的
kenneth
2012-12-06 11:54:20 +08:00
@livid 是不是self.request里面没有东西啊?

{% extends "base.html" %}
{% block title %}{% endblock %}
{% block head %}
{{ super() }}
{% endblock %}
{% block content %}
<form action="/upload" enctype="mutilpart/form-data" method="post">
<input type="file" name="file1" />
<input type="submit" value="上传" />
{{xsrf_form_html()}}
</form>
{% endblock %}
kenneth
2012-12-06 12:41:35 +08:00
@livid @binux
大家帮我分析看看,怎么就报错呢?
yujnln
2012-12-06 12:46:43 +08:00
你没有定义你的file1
<input type="file" name="file1" />
yujnln
2012-12-06 12:47:56 +08:00
错了,是这个 enctype="multipart/form-data"
kenneth
2012-12-06 12:48:31 +08:00
@yujnln 什么叫做没有定义file1,不是选择一本本地文件,然后点上传?
yujnln
2012-12-06 12:50:07 +08:00
@kenneth

是我看得太快了,的确定义了file1
错误在于 mutilpart 拼写错误,正确是multipart
你再试试?
kenneth
2012-12-06 12:50:09 +08:00
@yujnln 没明白啥意思,能否说清楚一些,错在哪里?
kenneth
2012-12-06 12:56:26 +08:00
感谢已发送,真是丢人。我面壁去了。谢谢各位。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/54216

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX