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)

php中世界最好的语言
Release: 2018-04-04 16:43:55
Original
1517 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template