"Sharing" compatible ie6-9 and modern browsers and asynchronous file upload plug-ins for Ios,android,pad and other touch-screen devices

Source: Internet
Author: User
Core Code
/** * This plugin is used for asynchronous upload files compatible with ie6-7-8-9 and modern browsers. * Note that the principle above ie6-7-8-9 is: * Add a new form and an IFRAME, then copy the file input box to the form each time you select it, and then submit the entire form so that you can achieve the same effect as the AJAX submission, * But there is no way to deal with, is in the client preview picture and judge the size of the file.
 Modern browsers are OK. * * var ajaxfileinput=function (opts) {var settings={container: ""///Put container for input box, inputfileelement: ""// The elemnt of the file input box for input file can be either a jquery element or a DOM element.
        Please note that because each upload generates an input input box inside the container, it is recommended that you do not put anything in the container except the file input box.
        , Onvalidate:function (filename,filedom) {return true; //This is the validation logic after selecting the file.
        If you return true, you can continue uploading the picture to a URL on the server, otherwise it will not execute.
        , max_size:5*1024*1024//Limit upload size-note that there is no way to get the size of the client on the ie6-9, so this property is useless.
        , URL: ""//upload the URL at the time. , Beforeupload:function (paras) {}//calls this method before uploading files.
        You can return an object, such as: {Birthday: "2016-2-05"} So, if there is this form of parameter, then whether in compatibility mode or Google and other modern browsers under normal mode, this parameter will be added to the form and upload.

    , Onerror:function (errormsg) {}, Oncomplete:function (Serverresult) {}};

    $.extend (settings,opts); var _container=$ (Settings.container);
    var _currentfilebutton={};
    _currentfilebutton=$ (settings.inputfileelement); var _tpl_file_html=_container.html ();


    Gets the HTML of the text box to prepare for a new text box to be replaced later.
    var Useriemode=false; if (window.
    filereader==undefined) {useriemode=true;
            var innertools={getbase4fromimgfile:function (file,callback) {var reader = new FileReader ();
                Reader.onload = function (e) {var base64img= e.target.result;
                var $img = $ ('  '). attr ("src", E.target.result)//$ (' #preview '). Empty (). Append ($img)
                if (callBack) {callBack (base64img);
            }
            };
        Reader.readasdataurl (file);


    }
    };
    var _rid= "Rid_" +util.getrandomwords (5) + "_" +new Date (). GetTime ();
    var _form_id= "Form_" +_rid;

    var _ifr_id= "Ifr_" +_rid;
    var el_iframe={};
    var el_form={};


    var Isbusy=false;
        var _i_app={Init:function () {var me=this;
            if (Useriemode) {me.initieform ();

        } me.resetfileinput (Settings.inputfileelement);
        //--generates the required form form and iframe of ie6-9 for Ajax asynchronous submission.
            , Initieform:function () {var me=this; var _ifr_html= ' <iframe id= ' __ifr_id__ "name=" __ifr_id__ "style=" Position:absolute; opacity:0.0; visibility:visible; left:0;top:0; width:100px; height:50px; "
            ></iframe> ';
            _ifr_html=_ifr_html.replace (/__ifr_id__/g,_ifr_id); var _form_html= ' <form id= "__form_id__" action= "__url__" target= "__ifr_id__" method= "post" enctype= "multipart/

            Form-data "style=" border:1px solid; "></form>";
            _form_html=_form_html.replace (/__ifr_id__/g,_ifr_id);
            _form_html=_form_html.replace (/__form_id__/g,_form_id);

            _form_html=_form_html.replace (/__url__/g,settings.url);
            el_form=$ (_form_html); el_iframe=$ (_ifr_html);
            $ (document.body). Append (El_form);


            $ (document.body). Append (El_iframe);
            --initialization of an IFRAME for AJAX-related operations.

        Me.initiframeloaded ();
        //--initialization of the IFRAME onload related events.
            , Initiframeloaded:function () {var me=this;


            var Ifr_json=document.getelementbyid (_ifr_id);
                function Handle_return () {var doc = Ifr_json.contentdocument | | ifr_json.document;
                var _json_str=doc.body.innertext;
                var res={};


                    try{Res=json.parse (_JSON_STR);
                    Isbusy=false;
                    var _new_file_input=$ (_tpl_file_html);
                    Me.resetfileinput (_new_file_input);
                    _container.empty (). append (_new_file_input);
                Settings.oncomplete (RES);

                    catch (ex) {res=_json_str;
                 Isbusy=false;   var _new_file_input=$ (_tpl_file_html);
                    Me.resetfileinput (_new_file_input);

                    _container.empty (). append (_new_file_input);
                Settings.onerror (_JSON_STR);
                    } if (ifr_json.attachevent) {ifr_json.attachevent ("onload", function () {
                Handle_return ();
            });
                else {ifr_json.onload = function () {Handle_return ();
            };
        }//--upload, with IFrame and form method.

            , Uploadbyform:function (paras) {var me=this;
            El_form.empty ();
            El_form.append (' <input type= ' submit "value=" submitted ">");
                for (var key in paras) {var _hide_val=$ (' <input type= ' hidden ' value= ' "name= '" ' +key+ ' "> ');
                _hide_val.val (Paras[key]);
            El_form.append (_hide_val); } if (Util.checkempty (_curRentfilebutton.attr ("name")) {_currentfilebutton.attr ("name", "file");

            } el_form.append (_currentfilebutton);
            settimeout (function () {el_form[0].submit ();

        },20);

            }, Uploadbyhttprequest:function (paras) {var me=this;

            var file=$ (_currentfilebutton) [0].files[0];
            var xhr = new XMLHttpRequest ();
                function UploadFile () {var fd = new FormData ();
                var _uploadkey= "file"; if (Util.checkempty (_currentfilebutton.attr ("name")) ==false) {_uploadkey=_currentfilebutton.attr ("name"
                );


                } fd.append (_uploadkey, file);
                for (var key in paras) {fd.append (Key,paras[key]);
                } Xhr.upload.addEventListener ("Progress", uploadprogress, false); Xhr.addeventlistener ("Load", Uploadcomplete, false);
                Xhr.addeventlistener ("Error", uploadfailed, false);
                Xhr.addeventlistener ("Abort", uploadcanceled, false);
                Xhr.open ("POST", Settings.url);
            Xhr.send (FD); } function Uploadprogress (evt) {if (evt.lengthcomputable) {var percentc
                    Omplete = Math.Round (evt.loaded * 100/evt.total);
                    Uploaditemobject.setprogress (PercentComplete);
                document.getElementById (' Progressnumber '). InnerHTML = percentcomplete.tostring () + '% ';
                    else {//document.getelementbyid (' Progressnumber '). InnerHTML = ' unable to compute ';
                Uploaditemobject.setstatetips ("Unknown Upload progress"); } function Uploadcomplete (evt) {/* This event is raised the server send B
           ACK a response * *//alert (Evt.target.responseText);     The/*1.xhr.readystate:xmlhttprequest state, which is equal to 4, indicates that the data has been received after 2.xhr.status: state, and 200 for normal 3.xhr.
                Responsetext:server the text data of the response///console.log (evt.target.status);
                Console.log (evt.target.readyState);
                Console.log (Xhr.status);
                    if (evt.target.status!=200) {isbusy=false;
                    var _new_file_input=$ (_tpl_file_html);
                    Me.resetfileinput (_new_file_input);
                    _container.empty (). append (_new_file_input);
                    Settings.onerror (evt.target.status+ "error");
                Uploaditemobject.showerror (evt.target.status+ "error");
                    } else{var res_json= "";
                        try{Res_json=json.parse (Evt.target.responseText);
                        Isbusy=false;
                        var _new_file_input=$ (_tpl_file_html); Me.resetfilEInput (_new_file_input);
                        _container.empty (). append (_new_file_input);
                    Settings.oncomplete (Res_json);
                        catch (ex) {res_json=evt.target.responsetext;
                        Isbusy=false;
                        var _new_file_input=$ (_tpl_file_html);
                        Me.resetfileinput (_new_file_input);
                        _container.empty (). append (_new_file_input);
                    Settings.onerror (Res_json); }} function uploadfailed (evt) {//alert ("There was" error
                Attempting to upload the file. ");
                Uploaditemobject.showerror ();
            Settings.onerror ("Upload failed"); function uploadcanceled (evt) {//alert ("The upload has been by the user or the canceled
                Wser dropped the connection. "); UploaditemObject.showerror ();

            } uploadfile ();
            Isbusy=false;
            var _new_file_input=$ (_tpl_file_html);
            Me.resetfileinput (_new_file_input);
        _container.empty (). append (_new_file_input);
        //--to reset the Upload button event, note that this method invocation is essential if you want to hack the onchange event.
            , Resetfileinput:function (__file_input) {var me=this;
            var _fileinput=$ (__file_input);
            var _filedom=_fileinput[0];

            _currentfilebutton=_fileinput;
                $ (_fileinput). Change (function () {//if (isbusy) {//return;

                }//isbusy=true;

                var _fake_path=_filedom.value;
                var __thefilename= ""; if (Util.checkempty (_fake_path)) {} else{if (_fake_path.indexof ("\")!
                        =-1) {var arr2=_fake_path.split ("\"); __thefilename=ARR2[ARR2.LENGTH-1];
                        else if (_fake_path.indexof ("/")!=-1) {var arr2=_fake_path.split ("/");
                    __THEFILENAME=ARR2[ARR2.LENGTH-1]; } if (Settings.onvalidate (__thefilename,_filedom) ==false) {ISBUSY=FA
                    Lse
                    var _new_file_input=$ (_tpl_file_html);
                    Me.resetfileinput (_new_file_input);

                    _container.empty (). append (_new_file_input);
                Return
                    } if (Util.checkempty (_fake_path) ==true) {var _new_file_input=$ (_tpl_file_html);
                    Me.resetfileinput (_new_file_input);
                    _container.empty (). append (_new_file_input);
                Return
                } var _paras={};


                Settings.beforeupload (_paras); if (Useriemode) {
                    Me.uploadbyform (_paras);
                } else{Me.uploadbyhttprequest (_paras);
        }




            });
    }
    };
_i_app.init ();

 }
HTML code
<%@ page contenttype= "Text/html;charset=utf-8" language= "java"%>  
Upload processing Code 
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%>
<%@ page import=" java.util.*,java.io.* "%> <%@
page Import = "Java.text.SimpleDateFormat"%>
<%@ page import= "org.apache.commons.fileupload.*"%> <%@
page Import= "org.apache.commons.fileupload.disk.*"%>
<%@ page import= "Org.apache.commons.fileupload.servlet" . * "%>
<%@ page import=" Com.alibaba.fastjson.JSONObject "%> <%-/**
     * Kindeditor JSP
     *
     * This JSP program is a demo program, it is recommended not directly in the actual project to use.
     * If you are sure to use this program directly, please carefully confirm the relevant security settings before use.
     * * *

//File Save directory path
    String savepath = Application.getrealpath ("/") + "uploads/";

File save directory URL
    String saveurl  = Request.getcontextpath () + "/uploads/";
    System.out.println (Savepath);

Defines the file extensions that are allowed
    to be uploaded hashmap<string, string> extmap
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.