1直接form提交给后台处理
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>form-upload</title>
</head>
<body>
注意form的enctype类型"multipart/form-data"
<form action="/form_upload" method="post" enctype="multipart/form-data"> <input type="file" name="file"/> <input type="submit", value="上传"/> </form> </body> </html> 后台post方法统一处理代码如下:
class FormRequest_handle(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
self.render('iframe_upload.html', status='') def post(self, *args, **kwargs):
print('post')
file_data = self.request.files['file']#读出了的文件是数组里面的是字典形式[{'filename':'xxx','body':'xxxxxxxxxxxxx'}]
for meta in file_data:
filename = meta['filename']
print(filename, file_data)
with open(os.path.join('static', filename), 'wb') as up:
up.write(meta['body'])
self.write('upload success') settings = {
'template_path':'views',
'static_path':'static',
# 'xsrf_cookies':True,此处测试csrf跨站伪造请求攻击请忽略
}
if __name__ == '__main__':
application = tornado.web.Application([
# (r'/index', Indexhandle),
# (r'/manager', Managerdhandle),
# (r'/csrf', Csrf_handle),
# (r'/xml', XmlHttpRequest_handle),
(r'/iframe',FormRequest_handle), ], **settings) application.listen(8089)
tornado.ioloop.IOLoop.instance().start()
2.伪ajax(iframe) 此方法发送请求不刷新页面,利用iframe 的局部刷新特性,对浏览器兼容性更好
<body>
<form id="myform" action="/iframe" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="button" value="上传" onclick="redirect()"/>
<iframe id="myiframe" name="my_iframe"></iframe>
</form>
<script src="{{static_url('jquery-3.2.1.js')}}"></script>
<script>
function redirect() {
// document.getElementById('myiframe').onload = test;#执行完iframe立即执行test函数
$('#myiframe').onload = test;
document.getElementById('myform').target = 'my_iframe';//此处等于IDmyframe会有不同
document.getElementById('myform').submit();
// $('#myform').submit();
}
function test() {
var t = $('#myiframe').contents().find('body').text();
console.log(t)
}
</script>
</body>