Home Web Front-end JS Tutorial Detailed explanation of how to implement file upload using Ajax and form+iframe

Detailed explanation of how to implement file upload using Ajax and form+iframe

May 24, 2018 am 10:34 AM
ajax document

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);
}
}
};
Copy after login

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>
Copy after login

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": {
...
}
}
Copy after login

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:

$(&#39;iframe&#39;).on(&#39;load&#39;, function() {
var responseText = $(&#39;iframe&#39;)[0].contentDocument.body.textContent;
var responseData = JSON.parse(responseText) || {};
if (responseData.isSuccess == true || responseData.code == 200) {
//success
} else {
//error 
}
});
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can Tmp format files be deleted? Can Tmp format files be deleted? Feb 24, 2024 pm 04:33 PM

Tmp format files are a temporary file format usually generated by a computer system or program during execution. The purpose of these files is to store temporary data to help the program run properly or improve performance. Once the program execution is completed or the computer is restarted, these tmp files are often no longer necessary. Therefore, for Tmp format files, they are essentially deletable. Moreover, deleting these tmp files can free up hard disk space and ensure the normal operation of the computer. However, before deleting Tmp format files, we need to

What to do if the 0x80004005 error code appears. The editor will teach you how to solve the 0x80004005 error code. What to do if the 0x80004005 error code appears. The editor will teach you how to solve the 0x80004005 error code. Mar 21, 2024 pm 09:17 PM

When deleting or decompressing a folder on your computer, sometimes a prompt dialog box &quot;Error 0x80004005: Unspecified Error&quot; will pop up. How should you solve this situation? There are actually many reasons why the error code 0x80004005 is prompted, but most of them are caused by viruses. We can re-register the dll to solve the problem. Below, the editor will explain to you the experience of handling the 0x80004005 error code. Some users are prompted with error code 0X80004005 when using their computers. The 0x80004005 error is mainly caused by the computer not correctly registering certain dynamic link library files, or by a firewall that does not allow HTTPS connections between the computer and the Internet. So how about

Different uses of slashes and backslashes in file paths Different uses of slashes and backslashes in file paths Feb 26, 2024 pm 04:36 PM

A file path is a string used by the operating system to identify and locate a file or folder. In file paths, there are two common symbols separating paths, namely forward slash (/) and backslash (). These two symbols have different uses and meanings in different operating systems. The forward slash (/) is a commonly used path separator in Unix and Linux systems. On these systems, file paths start from the root directory (/) and are separated by forward slashes between each directory. For example, the path /home/user/Docume

How to transfer files from Quark Cloud Disk to Baidu Cloud Disk? How to transfer files from Quark Cloud Disk to Baidu Cloud Disk? Mar 14, 2024 pm 02:07 PM

Quark Netdisk and Baidu Netdisk are currently the most commonly used Netdisk software for storing files. If you want to save the files in Quark Netdisk to Baidu Netdisk, how do you do it? In this issue, the editor has compiled the tutorial steps for transferring files from Quark Network Disk computer to Baidu Network Disk. Let’s take a look at how to operate it. How to save Quark network disk files to Baidu network disk? To transfer files from Quark Network Disk to Baidu Network Disk, you first need to download the required files from Quark Network Disk, then select the target folder in the Baidu Network Disk client and open it. Then, drag and drop the files downloaded from Quark Cloud Disk into the folder opened by the Baidu Cloud Disk client, or use the upload function to add the files to Baidu Cloud Disk. Make sure to check whether the file was successfully transferred in Baidu Cloud Disk after the upload is completed. That's it

What is hiberfil.sys file? Can hiberfil.sys be deleted? What is hiberfil.sys file? Can hiberfil.sys be deleted? Mar 15, 2024 am 09:49 AM

Recently, many netizens have asked the editor, what is the file hiberfil.sys? Can hiberfil.sys take up a lot of C drive space and be deleted? The editor can tell you that the hiberfil.sys file can be deleted. Let’s take a look at the details below. hiberfil.sys is a hidden file in the Windows system and also a system hibernation file. It is usually stored in the root directory of the C drive, and its size is equivalent to the size of the system's installed memory. This file is used when the computer is hibernated and contains the memory data of the current system so that it can be quickly restored to the previous state during recovery. Since its size is equal to the memory capacity, it may take up a larger amount of hard drive space. hiber

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

Detailed explanation of the role of .ibd files in MySQL and related precautions Detailed explanation of the role of .ibd files in MySQL and related precautions Mar 15, 2024 am 08:00 AM

Detailed explanation of the role of .ibd files in MySQL and related precautions MySQL is a popular relational database management system, and the data in the database is stored in different files. Among them, the .ibd file is a data file in the InnoDB storage engine, used to store data and indexes in tables. This article will provide a detailed analysis of the role of the .ibd file in MySQL and provide relevant code examples to help readers better understand. 1. The role of .ibd files: storing data: .ibd files are InnoDB storage

Detailed explanation of log viewing command in Linux system! Detailed explanation of log viewing command in Linux system! Mar 06, 2024 pm 03:55 PM

In Linux systems, you can use the following command to view the contents of the log file: tail command: The tail command is used to display the content at the end of the log file. It is a common command to view the latest log information. tail [option] [file name] Commonly used options include: -n: Specify the number of lines to be displayed, the default is 10 lines. -f: Monitor the file content in real time and automatically display the new content when the file is updated. Example: tail-n20logfile.txt#Display the last 20 lines of the logfile.txt file tail-flogfile.txt#Monitor the updated content of the logfile.txt file in real time head command: The head command is used to display the beginning of the log file

See all articles