


Detailed explanation of how to implement file upload using Ajax and form+iframe
The file upload function is often used in projects. This article will introduce to you two implementations of file upload-Ajax and form iframe. Friends who are interested can learn together
Since the introduction of html5, files Uploading becomes very simple. It is very convenient to solve the file upload function that needs to be used in the project. HTML5 supports multiple image uploads, ajax uploads, previews of images before uploading, and drag-and-drop image uploading. It is purely implemented using the file control and has very little JS code. It is difficult not to be praised!
HTML5Ajax upload
html5 upload implementation requires file control and XMLHttpRequest request . The following is an upload plug-in I encapsulated:
function fileUpload(options) { var opts = options || {}; var func = function() {}; this.fileInput = opts.fileInput || null; this.url = opts.url || ''; this.fileList = []; this.onFilter = opts.onFilter || function(f) {return f;}; //选择文件组的过滤方法 this.onSelect = opts.onSelect || func; //文件选择后 this.onProgress = opts.onProgress || func; //文件上传进度 this.onSuccess = opts.onSuccess || func; //文件上传成功时 this.onFailure = opts.onFailure || func; //文件上传失败时; this.onComplete = opts.onComplete || func; //文件全部上传完毕时 this.init(); } fileUpload.prototype = { dealFiles: function(e) { //获取要上传的文件数组(用户选择文件后执行) var files = e.target.files || e.dataTransfer.files; this.fileList = this.onFilter(files); for(var i = 0, file; file = this.fileList[i]; i++){ //增加唯一索引值 file.index = i; } this.onSelect(this.fileList); return this; }, removeFile: function(fileDelete) { //删除某一个文件 var arrFile = []; for(var i = 0, file; file = this.fileList[i]; i++){ if (file != fileDelete) { arrFile.push(file); } } this.fileList = arrFile; return this; }, removeAll: function() { //清空文件队列 this.fileList = []; return this; }, uploadFile: function() { //上传文件 var me = this; for(var i = 0, file; file = this.fileList[i]; i++){ (function(file) { var formData = new FormData(); var xhr = new XMLHttpRequest(); if (xhr.upload) { xhr.upload.addEventListener("progress", function(e) { // 上传中 me.onProgress(file, e.loaded, e.total); }, false); xhr.onreadystatechange = function(e) { // 文件上传成功或是失败 if (xhr.readyState == 4) { if (xhr.status == 200) { me.onSuccess(file, xhr.responseText); me.removeFile(file); if (!me.fileList.length) { me.onComplete(); //上传全部完毕。执行回调 } } else { me.onFailure(file, xhr.responseText); } } }; // 开始上传 formData.append('file', file); xhr.open("POST", me.url, true); xhr.send(formData); } })(file); } }, init: function() { var me = this; //文件选择控件选择 if (me.fileInput) { me.fileInput.addEventListener("change", function(e) { me.dealFiles(e); }, false); } } };
I believe you have also seen that formData appears in the code. This is the magic of html5. . With the help of formData, you can easily implement asynchronous multi-file upload function without refresh and support preview images. Moreover, it is gratifying that many browsers now support HTML5.
but! ! ! Versions below ie9 are not supported! !
In addition, the above method also has a drawback. Because it uses ajax upload method, it cannot support cross-domain upload. If you must meet these two business scenarios, then try the following The method is to use form and iframe to upload. Let’s take a closer look:
form form submission to iframe
html code:
<iframe name="demoIframe" style="display:none"></iframe> <form target="demoIframe" action="upload.php" method="post" enctype="multipart/form-data"> <input class="filename" type="file" name="fileLabel"> <input type="submit" value="提交"> </form>
We click submit and you can see the following request:
has been submitted File Upload. Then, adding this upload.php interface is available, and if the upload is successful, it will return:
{ "code": "200", "success": true, "data": { ... } }
How do we get the return value, so What's the next step? Because we uploaded it to an iframe, we only need to listen to the load event of the iframe. If there is a return value, we can get it for further processing. Look at the js code:
$('iframe').on('load', function() { var responseText = $('iframe')[0].contentDocument.body.textContent; var responseData = JSON.parse(responseText) || {}; if (responseData.isSuccess == true || responseData.code == 200) { //success } else { //error } });
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Quick solution to Ajax submission of garbled characters under IE
Ajax form asynchronous upload file example code
Cascade operation of drop-down menu
The above is the detailed content of Detailed explanation of how to implement file upload using Ajax and form+iframe. For more information, please follow other related articles on the PHP Chinese website!

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Chinese version
Chinese version, very easy to use
