Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How QTcpSocket receive file from JS(XMLHttpRequest.send) or HTML(Form.submit)



  • JS(XMLHttpRequest.send)

    <html>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <title>Upload File</title>
    <input type="file" id="file"><button id="button_upload" οnclick="upload()">Upload</button>
    <div id="msg"></div>
    <script>
    var file = document.getElementById("file");
    var button_upload = document.getElementById("button_upload");
    var msg = document.getElementById("msg");
    button_upload.addEventListener('click', function() {
       upload();
    });
    
    function upload(){
    	msg.innerHTML = "Upload start";	
    	var fileReader = new FileReader();
    	var XHR = new XMLHttpRequest();
    	XHR.onreadystatechange = function(){
    		msg.innerHTML = msg.innerHTML + "<br>\nXHR('readyState': " + XHR.readyState + " , 'status': " + XHR.status + ")";
    		if(XHR.readyState == 4){
    			if(XHR.status == 200){
    				msg.innerHTML = msg.innerHTML + "<br>\n文件上传成功";
    				msg.innerHTML = msg.innerHTML + "<br>\n" + XHR.responseText;  
    			}else{
    				msg.innerText = "文件上传失败了";
    			}
    		}
    	};
    	fileReader.onloadstart = function(e) {
    		msg.innerHTML = msg.innerHTML + "<br>\nonloadstart";
    	}
    	fileReader.onloadend = function(e) {
    		msg.innerHTML = msg.innerHTML + "<br>\nonloadend";		
    		msg.innerHTML = msg.innerHTML + "<br>\n" + url;
    		XHR.open("POST", "/", true);
    		XHR.setRequestHeader("Content-type", "application/octet-stream"); //流类型
    		//XHR.setRequestHeader("Content-length", file.files[0].size);     //文件大小
    		XHR.setRequestHeader("Filename", encodeURI(file.files[0].name)); //兼容中文
    		XHR.send(e.target.result);
    	};
    	fileReader.onerror = function(e){
    		msg.innerHTML = msg.innerHTML + "<br>\n" + e;
    	};
    	fileReader.οnlοad = function(e){//不触发
    		msg.innerHTML = msg.innerHTML + "<br>\nοnlοad";
    	};
    	fileReader.onprogress = function(e){
    		msg.innerHTML = msg.innerHTML + "<br>" + e.loaded*100 / e.total + "%";
    	};
    	fileReader.readAsArrayBuffer(file.files[0]);
    }
    </script>
    </html>
    

    HTML(Form.submit)

    <html>
    <body>
    <form action="/" method="post" enctype="multipart/form-data">
    <input type="file" name="file" id="file"><input type="submit">
    </form>
    </body>
    </html>
    

Log in to reply