Home Web Front-end JS Tutorial How to implement file upload with Ajax and form+iframe (detailed explanation with pictures and text)

How to implement file upload with Ajax and form+iframe (detailed explanation with pictures and text)

Apr 04, 2018 pm 04:43 PM
ajax upload

This time I will bring you the method of file upload with Ajax and form+iframe (detailed explanation with pictures and texts). What are the precautions for Ajax and form+iframe to implement file upload? , the following is a practical case, let’s take a look.

Since the advent of html5, file uploading has become 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 hard not to praise it!

HTML5Ajax upload

The upload implementation of html5 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, it is easy to 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 the 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 submitted 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:

The file has been uploaded. 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 to perform 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 
}
});
Copy after login
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

How beforeSend improves user experience

SpringMVC environment Ajax asynchronous request JSON method

The above is the detailed content of How to implement file upload with Ajax and form+iframe (detailed explanation with pictures and text). 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)

How to upload lyrics to QQ Music How to upload lyrics to QQ Music Feb 23, 2024 pm 11:45 PM

With the advent of the digital age, music platforms have become one of the main ways for people to obtain music. However, sometimes when we listen to songs, we find that there are no lyrics, which is very disturbing. Many people hope that lyrics can be displayed when listening to songs to better understand the content and emotions of the songs. QQ Music, as one of the largest music platforms in China, also provides users with the function of uploading lyrics, so that users can better enjoy music and feel the connotation of the songs. The following will introduce how to upload lyrics on QQ Music. first

Simple steps to upload your own music on Kugou Simple steps to upload your own music on Kugou Mar 25, 2024 pm 10:56 PM

1. Open Kugou Music and click on your profile picture. 2. Click the settings icon in the upper right corner. 3. Click [Upload Music Works]. 4. Click [Upload Works]. 5. Select the song and click [Next]. 6. Finally, click [Upload].

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

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.

How to improve computer upload speed How to improve computer upload speed Jan 15, 2024 pm 06:51 PM

Upload speed becomes very slow? I believe this is a problem that many friends will encounter when uploading things on their computers. If the network is unstable when using a computer to transfer files, the upload speed will be very slow. So how can I increase the network upload speed? Below, the editor will tell you how to solve the problem of slow computer upload speed. When it comes to network speed, we all know that the speed of opening web pages, download speed, and upload speed are also very critical. Especially some users often need to upload files to the network disk, so a fast upload speed will undoubtedly save you a lot of money. Less time, what should I do if the upload speed is slow? Below, the editor brings you pictures and texts on how to deal with slow computer upload speeds. How to solve the problem of slow computer upload speed? Click "Start--Run" or "Window key"

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

How to take photos and upload them on computer How to take photos and upload them on computer Jan 16, 2024 am 10:45 AM

As long as the computer is equipped with a camera, it can take pictures, but some users still don't know how to take pictures and upload them. Now I will give you a detailed introduction to the method of taking pictures on the computer, so that users can upload the pictures wherever they want. How to take photos and upload them on a computer 1. Mac computer 1. Open Finder and click the application on the left. 2. After opening, click the Camera application. 3. Just click the photo button below. 2. Windows computer 1. Open the search box below and enter camera. 2. Then open the searched application. 3. Click the photo button next to it.

See all articles