1 Direct form submission to background processing
1 <! DOCTYPE html> 2 "en"> 3 4 <meta charset="UTF-8"> 5 <title>form-upload</title > 6 7 <body>
Note the enctype type "multipart/form-data" of the form
8<form action="/form_upload"Method="Post"Enctype="Multipart/form-data">9<input type="file"Name="file"/>Ten<input type="Submit", value="Upload"/> One</form> A</body> -
The background Post method uniform processing code is as follows:
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 ']# The read out file is the dictionary form inside the array [{' filename ': ' xxx ', ' body ': ' xxxxxxxxxxxxx '}] for meta in file_data:filename = Meta[' fil Ename '] 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, here Test csrf cross-site forgery request attack Please ignore}if __name__ = = ' __main__ ': application = Tornado.web.Applicatio N ([# (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. Pseudo-Ajax (IFRAME) This method sends a request without refreshing the page, leveraging the local refresh feature of the IFRAME for better browser compatibility
1<body>2<form id="MyForm"action="/iframe"Method="Post"Enctype="Multipart/form-data">3<input type="file"Name="file"/>4<input type="Button"Value="Upload"onclick="Redirect ()"/>5<iframe id="Myiframe"Name="My_iframe"></iframe>6</form>7<script src="{{Static_url (' Jquery-3.2.1.js ')}}"></script>8<script>9 function Redirect () {Tendocument.getElementById ('Myiframe'). onload =test; #执行完iframe立即执行test函数 One$('#myiframe'). onload =test; Adocument.getElementById ('MyForm'). target ='My_iframe';//here equals Idmyframe will have different -document.getElementById ('MyForm'). Submit (); -// $('#myform'). Submit (); the } - function Test () { -var t = $ ('#myiframe'). Contents (). Find ('Body'). text (); - Console.log (t) + } -</script> +</body>
Tornado file Upload form, pseudo Ajax (IFRAME)