javascript前端向python tornado后端传文件

html:

<form>
                        <input type="file" id="files" name="file">
                        <a id="cfmbtn" class="btn btn-primary pull-right" onclick="onProcessFile()">confirm</a>
                        <div class="clearfix" id="loginError" style="color:red;font:bold"></div>
                    </form>


js:

function onProcessFile(){  
	var xhr = new XMLHttpRequest();
	
	xhr.onreadystatechange = function()
	{
	    if(xhr.readyState == 4)
	    {
	    	if(xhr.status ==200 || xhr.status == 304)
	    	{
	    		console.log(xhr.responseText);
	    		var respon = JSON.parse(xhr.responseText);
	    		//console.log(respon);
	    		console.log(respon.res.platenum)
	    		if(respon.issuccess == "success")
	    		{
	    			$("#loginError").html("succeed!");
	    		}
	    		else if(respon.issuccess == "no_file")
	    		{
	    			$("#loginError").html("no file received!");
	    		}
	    		else
	    		{
	    			$("#loginError").html("error");
	    		}
	    	}
	    	else
	    	{
	    		alert("Request was unsuccessful:"+xhr.status);
	    	}
	    }
	}

	var files = document.getElementById('files').files;

    if (!files.length) 
    {
      alert('Please select a file!');
      return;
    }
    var file = files[0];

    var form = new FormData();
    form.append("infile", file);
    xhr.open("post", "/login", false);
    xhr.send(form);
}


python后端:

class LoginHandler(tornado.web.RequestHandler):
    def get(self):
        pass
    def post(self):
        if not 'infile' in self.request.files:
            respon = {'issuccess':'no_file'}
            respon_json = tornado.escape.json_encode(respon)
            self.write(respon_json)
        else:
            infile = self.request.files['infile'][0]
            tmpfile = open("tmp.jpg", "wb")
            tmpfile.write(infile['body'])
            tmpfile.flush()
            tmpfile.close()
            res = client.analyseImg("tmp.jpg")
            respon = {'issuccess':'success', 'res':res}
            respon_json = tornado.escape.json_encode(respon)
            self.write(respon_json)



你可能感兴趣的:(javascript前端向python tornado后端传文件)