Details about how to upload files using Ajax and form + iframe (two methods), ajaxiframe

Source: Internet
Author: User

Details about how to upload files using Ajax and form + iframe (two methods), ajaxiframe

Since html5 was available, file upload has become very simple. It easily solves the file upload function required by the project. HTML5 supports multi-Image Upload and ajax upload. It also supports preview of images before uploading. It also supports drag-and-drop upload of images, and is purely implemented using the file control. JS code is rare, it's hard not to let people praise it!

HTML5Ajax upload

Html5 upload implementation requires the file control and XMLHttpRequest request. The following is an upload plug-in encapsulated by me:

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 ;}; // select the file group filtering method this. onSelect = opts. onSelect | func; // this. onProgress = opts. onProgress | func; // File Upload progress this. onSuccess = opts. onSuccess | func; // this. onFailure = op Ts. onFailure | func; // when the file upload fails; this. onComplete = opts. onComplete | func; // this. init ();} fileUpload. prototype = {dealFiles: function (e) {// obtain the array of files to be uploaded (executed after the user selects the file) var files = e.tar get. files | e. dataTransfer. files; this. fileList = this. onFilter (files); for (var I = 0, file; file = this. fileList [I]; I ++) {// Add the unique index value file. index = I;} this. onSelect (this. fileList); return this;}, removeFile: function (FileDelete) {// delete a file 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 () {// clear the file queue this. fileList = []; return this;}, uploadFile: function () {// Upload file 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) {// upload me. onProgre Ss (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 (); // upload is complete. Execute callback} else {me. onFailure (file, xhr. responseText) ;}}; // starts to upload formData. append ('file', file); xhr. open ("POST", me. url, true); xhr. send (formData) ;}} (file) ;}, init: function () {var me = this; // select if (me. fileInput) {me. fileInput. addEventListener ("change", function (e) {me. dealFiles (e) ;}, false );}}};

I believe you can also see that formData appears in the code, which is the magic of html5. With formData, you can easily Implement Asynchronous refreshing and support multi-File Upload for preview images. Furthermore, we are pleased that many browsers now support html5.

But !!! Versions earlier than ie9 are not supported !!

In addition, the above method also has a drawback. Because ajax is used for uploading, cross-origin upload is not supported. If you must meet these two business scenarios, try the following method and use form and iframe to upload. Let's take a closer look:

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 =" submit "> </form>

Click Submit to view the following request:

The file has been uploaded. The upload. php interface is available. If the upload is successful, the following message is returned:

{"code": "200","success": true,"data": {...}} 

How can we get the return value and perform the next operation? Because we uploaded the object to the iframe, we only need to listen to the iframe load event. If there is a returned value, we can get it for further processing. View 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 }});

In this way, we have completed a file upload operation that supports all browsers. Thank you very much for your support for the help House website!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.