


There are two ways to send a request, one is to use ajax, the other is to use form submission. If the default form submission is not processed, the page will be redirected. Let’s use a simple demo to illustrate:
html is as shown below, the requested path action is "upload", and no other processing will be done:
<form method="POST" action="upload" enctype="multipart/form-data"> 名字 <input type="text" name="user"></input> 头像 <input type="file" name="file"></input> <input type="submit" id="_submit" value="提交"></input> </form>
The server (node) response directly returns: "Recieved form data", the demonstration is as follows:
You can see that by default, the form requests upload and redirects to upload at the same time. But in many cases, we hope that the form request will be like ajax and will not redirect or refresh the page. Like the above scenario, after the upload is completed, the avatar selected by the user is displayed on the current page.
The first solution is to use html5's FormData, encapsulate the data in the form into the FormData object, and then send it out by POST. As shown in the following code, respond to the click event of the submit button. Line 6 of the code obtains the DOM object of the form, then constructs an instance of FormData on line 8, and sends the form data on line 18.
document.getElementById("_submit").onclick = function(event){ //取消掉默认的form提交方式 if(event.preventDefault) event.preventDefault(); else event.returnValue = false; //对于IE的取消方式 var formDOM = document.getElementsByTagName("form")[]; //将form的DOM对象当作FormData的构造函数 var formData = new FormData(formDOM); var req = new XMLHttpRequest(); req.open("POST", "upload"); //请求完成 req.onload = function(){ if(this.status === ){ //对请求成功的处理 } } //将form数据发送出去 req.send(formData); //避免内存泄漏 req = null; }
After the upload is successful, the service will return the access address of the image, and add 14 lines to handle the successful request: display the uploaded image above the submit button:
var img = document.createElement("img"); img.src = JSON.parse(this.responseText).path; formDOM.insertBefore(img, document.getElementById("_submit"));
Example:
If you use jQuery, you can use formData as the data parameter of ajax, and set contentType: false and processData: false at the same time to tell jQuery not to process the request header and the data sent.
It seems that this submission method is the same as ajax, but it is not exactly the same. There are three data formats for form submission. If you want to upload a file, it must be multipart/form-data, so http in the form submission request above The Content-Type in the header information is multipart/form-data, while the ordinary ajax submission is application/json. The complete Content-Type submitted by the form is as follows:
"content-type":"multipart/form-data; boundary=------WebKitFormBoundaryYOE7pWLqdFYSeBFj"
In addition to multipart/form-data, a boundary is also specified. The purpose of this boundary is to distinguish different fields. Since the FormData object is opaque, calling JSON.stringify will return an empty object {}. At the same time, FormData only provides the append method, so the actual uploaded content of FormData cannot be obtained, but it can be viewed through the data received by analysis tools or services. . If you upload a text file above, the original format of the POST data received by the service is as follows:
------WebKitFormBoundaryYOE7pWLqdFYSeBFj
Content-Disposition: form-data; name="user"
abc
------WebKitFormBoundaryYOE7pWLqdFYSeBFj
Content-Disposition: form-data; name="file"; filename="test.txt"
Content-Type: text/plain
This is the content of a text file.
------WebKitFormBoundaryYOE7pWLqdFYSeBFj--
From the data received by the above service, we can see the format submitted by FormData. Each field is separated by boundary and ends with --. For ajax requests, the data format sent out is customized, usually with key=value and an & in the middle:
var req = new XMLHttpRequest(); var sendData = "user=abc&file=这是一个文本文件的内内容"; req.open("POST", "upload"); //发送的数据需要转义,见上面提到的三种格式 req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); req.send(sendData);
服务就会收到和send发出去的字符串一模一样的内容,然后再作参数解析,所以就得统一参数的格式:
user=abc&file=这是一个文本文件的内容
从这里可以看出POST本质上并不比GET安全,POST只是没有将数据放在网址传送而已。
考虑到FormData到了IE10才支持,如果要支持较低版本的IE,那么可以借助iframe。
文中一开始就说,默认的form提交会使页面重定向,而重定向的规则在target中指定,可以和a标签一样指定为"_blank",在新窗口中打开;还可以指定为一个iframe,在该iframe中打开。所以可以弄一个隐藏的iframe,将form的target指向这个iframe,当form请求完成时,返回的数据就会由这个iframe显示,正如上面在新页面显示的:"Recieved form data"。请求完成后,iframe加载完成,触发load事件,在load事件的处理函数里,获取该iframe的内容,从而拿到服务返回的数据了!拿到后再把iframe删掉。
在提交按钮的响应函数里,首先创建一个iframe,设置iframe为不可见,然后再添加到文档里:
var iframe = document.createElement("iframe"); iframe.width = 0; iframe.height = 0; iframe.border = 0; iframe.name = "form-iframe"; iframe.id = "form-iframe"; iframe.setAttribute("style", "width:0;height:0;border:none"); //放到document this.form.appendChild(iframe);
改变form的target为iframe的name值:
this.form.target = "form-iframe";
然后再响应iframe的load事件:
iframe.onload = function(){ var img = document.createElement("img"); //获取iframe的内容,即服务返回的数据 var responseData = this.contentDocument.body.textContent || this.contentWindow.document.body.textContent; img.src = JSON.parse(responseData).path; f.insertBefore(img, document.getElementById("_submit")); //删掉iframe setTimeout(function(){ var _frame = document.getElementById("form-iframe"); _frame.parentNode.removeChild(_frame); }, 100); //如果提示submit函数不存在,请注意form里面是否有id/value为submit的控件 this.form.submit(); }
第二种办法到这里就基本可以了,但是如果看163邮箱或者QQ邮箱上传文件的方式,会发现和上面的两种方法都不太一样。用httpfox抓取请求的数据,会发现上传的内容的格式并不是上面说的用boundary隔开,而是直接把文件的内容POST出去了,而文件名、文件大小等相关信息放在了文件的头部。如163邮箱:
POST Data:
this is a text
Headers:
Mail-Upload-name: content.txt
Mail-Upload-size: 15
可以推测它们应该是直接读取了input文件的内容,然后直接POST出去了。要实现这样的功能,可以借助FileReader,读取input文件的内容,再保留二进制的格式发送出去:
var req = new XMLHttpRequest(); req.open("POST", "upload"); //设置和邮箱一样的Content-Type req.setRequestHeader("Content-Type", "application/octet-stream"); var fr = new FileReader(); fr.onload = function(){ req.sendAsBinary(this.result); } req.onload = function(){ //一样,省略 } //读取input文件内容,放到fileReader的result字段里 fr.readAsBinaryString(this.form["file"].files[0]);
代码第13行执行读文件,读取完毕后触发第6行的load响应函数,第7行以二进制文本形式发送出去。由于sendAsBinary的支持性不是很好,可以自行实现一个:
if(typeof XMLHttpRequest.prototype.sendAsBinary === 'undefined'){ XMLHttpRequest.prototype.sendAsBinary = function(text){ var data = new ArrayBuffer(text.length); var uia = new UintArray(data, ); for (var i = ; i < text.length; i++){ uia[i] = (text.charCodeAt(i) & xff); } this.send(uia); } }
代码的关键在于第6行,将字符串转成8位无符号整型,还原二进制文件的内容。在执行了fr.readAsBinaryString之后,二进制文件的内容将会以utf-8的编码以字符串形式存放到result,上面的第6行代码将每个unicode编码转成整型(&0xff或者parseInt),存放到一个8位无符号整型数组里面,第8行把这个数组发送出去。如果直接send,而不是sendAsBinary,服务收到的数据将无法正常还原成原本的文件。
上面的实现需要考虑文件太大,需分段上传的问题。
关于FileReader的支持性,IE10以上支持,IE9有另外一套File API。
文章讨论了3种办法实现无刷新上传文件,分别是使用iframe、FormData和FileReader,支持性最好是的iframe,但是从体验的效果来看FormData和FileReader更好,因为这两者不用生成一个无用的DOM再删除,其中FormData最简单,而FileReader更加灵活。
下面给大家介绍iframe无刷新上传文件
form.html <form enctype="multipart/form-data" method="post" target="upload" action="upload.php" > <input type="file" name="uploadfile" /> <input type="submit" /> </form> <iframe name="upload" style="display:none"></iframe>

iframe加载慢的原因主要包括网络延迟、资源加载时间长、加载顺序、缓存机制以及安全策略等。详细介绍:1、网络延迟,当浏览器加载一个包含iframe的网页时,需要发送请求到服务器获取iframe中的内容,若网络延迟较高,那么获取内容的时间就会增加,从而导致iframe加载慢;2、资源加载时间长,资源的大小较大或者服务器响应时间较长时,加载速度会更加明显地变慢;3、加载顺序等等。

可以代替iframe的技术有Ajax、JavaScript库或框架、Web组件技术、前端路由和服务器端渲染等。详细介绍:1、Ajax是一种用于创建动态网页的技术。它可以通过在后台与服务器进行数据交换,实现页面的异步更新,而无需刷新整个页面,使用Ajax可以更加灵活地加载和显示内容,不再需要使用iframe来嵌入其他页面;2、JavaScript库或框架,如React等等。

当用户通过Safari浏览器访问电子邮件服务时,微软的Outlook正在macOS上下载一个名为“TokenFactoryIframe”的神秘文件。发现Outlook在每次访问时下载的“TokenFactoryIframe”文件的用户现已广泛报告此问题。Outlook每隔几秒或至少在每次访问Apple平台上的Outlook时都会下载此神秘文件。根据我们的调查结果,这似乎是由发布到Outlook的服务器端更新错误引起的问题,与Safari或macOS无关。微软在一份

Python中iframe是一种HTML标签,用于在网页中嵌入另一个网页或文档。在Python中,可以使用各种库和框架来处理和操作iframe,其中最常用的是BeautifulSoup库,可以轻松地从一个网页中提取出iframe的内容,并对其进行操作和处理。掌握如何处理和操作iframe对于Web开发和数据抓取都是非常有用的。

iframe嵌入播放器是一种在网页中嵌入视频播放器的技术。嵌入播放器的优点有:1、灵活性,通过使用iframe标签,可以将来自不同来源的视频媒体嵌入到同一个网页中;2、易用性,只需复制并粘贴嵌入代码,即可将播放器添加到网页中;3、可以通过设置参数来控制播放器的外观和行为;4、可以通过使用JavaScript来控制播放器的操作等等。

IE中的iframe是一种强大的工具,可以用于在网页中嵌入其他网页或文档,实现页面的分割和内容的展示。通过合理的使用和注意事项,可以充分发挥iframe的优势,提升网页的用户体验和功能性。

可以替代iframe的有Ajax请求、Web组件、框架和库、跨域通信、使用CSS布局和样式等。详细介绍:1、Ajax请求可以动态加载并显示其他网页或内容,而无需使用iframe,通过使用XMLHttpRequest对象或更现代的fetch API,可以实现异步加载内容,并将其插入到当前网页中的DOM树中,可以避免iframe的安全问题,并且可以更好地控制和操作加载的内容等等。

iframe禁用是指在网页中禁止使用iframe标签的功能。由于一些安全和隐私的考虑,有时候需要禁用iframe标签的使用,常见的禁用方法:1、通过设置X-Frame-Options响应头,表示不允许嵌入到任何iframe中;2、使用Content-Security-Policy,控制是否允许嵌入到iframe中;3、使用JavaScript禁用iframe标签等。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version
Chinese version, very easy to use

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
