In fact, before ajax appeared, web applications could also be refresh-free. At that time, this was mostly done through IFrame. Of course, after Ajax appeared, people flocked to the Ajax camp, and iFrame became less popular. But using iFrame to upload files without refreshing is indeed a good choice.
The solution is to handle the upload operation through a hidden iframe. I use ReactJS, amazeui, nodejs
1.html target points to the name of the iframe, which means that the upload operation is handed over to the iframe for processing.
<form id="supplyformFile" name="formFile" method="post" target="frameFile" encType="multipart/form-data"> <div className="am-form-file"> <button type="button" className="am-btn am-btn-default am-btn-sm"> <i className="am-icon-cloud-upload"></i> 选择要上传的文件 </button> <input type="file" id="fileUp" onChange={this.UploadSupplyer} name="fileUp" /> </div> <div id="supplyfile_div"></div> </form> <iframe id="frameFile" name="frameFile" style={{display: 'none'}}></iframe> <input type="hidden" id="supplyfile" />
2.JS processing submits the form after file selection
UploadSupplyer:function(){ var path = document.all.fileUp.value; if(!path){return false;} $('.loadinfo').html('<p>文件上传中...</p>').removeClass("none"); $('#supplyformFile').submit(); },
3.nodejs server processing, because the processing page is the nodejs server domain, there are cross-domain problems in the iframe, so you need to use the H5 postMessage method to pass parameters to the form page outside the iframe
var fname = req.files.fileUp.path.replace("publicfiles", "").replace("public/files/", ""); res.writeHead(200, {'Content-type' : 'text/html'}); res.write('<script>'); res.write('window.parent.postMessage("'+fname+'","*");'); res.end('</script>');
4.JS processing upload results
window.addEventListener('message',function(e){ var fname=e.data; $('#supplyfile').val(fname); $(".loadinfo").addClass("none"); $(".successinfo").html("<p>文件上传成功</p>").removeClass("none"); setTimeout(function() { $(".successinfo").addClass("none");}, 2000); $("#supplyfile_div").html('<span class="am-icon-file-o"></span> <a target="_blank" href="'+hosts+'/files/'+fname+'">供应商确认单</a>'); },false);
The above is the editor’s introduction to the operation of uploading files without refreshing by hiding iframe. I hope it will be helpful to everyone!