Layui File upload progress bar (analog)

Source: Internet
Author: User
Tags file upload progress bar

1. Modify the Upload Component JS (not measured)

81017471

Https://www.cnblogs.com/youmingkuang/p/9183528.html

https://fly.layui.com/jie/19430/

1. upload.js extension

Function using Ajax's XHR property implementation
This feature modifies the Upload.js file in modules
Features specific implementations:
Adding a listener function to the JS file

    Create a listener function     var xhronprogress=function (fun) {        xhronprogress.onprogress = fun;//Binding monitoring         //using closures for monitoring and binding        return function () {            //through $.AJAXSETTINGS.XHR (); Get XMLHttpRequest object            var xhr = $.ajaxsettings.xhr ();             Determine if the listener function is a function              if (typeof xhronprogress.onprogress!== ' function ')                   return xhr;               If you have a listener function and the XHR object supports binding, bind the listener function to                if (xhronprogress.onprogress && xhr.upload) {                      xhr.upload.onprogress = xhronprogress.onprogress;                }                return xhr;         }     }

Initializing uploads

Initialize upload upload.render ({     elem: ' Upload address '     , url:path+ '/upload/uploadvideo.do '     , accept: ' Video '    , size: 512000    , Auto:false    , Xhr:xhronprogress    , progress:function (value) {//Upload progress Callback value progress value        Element.progress (' demo ', value+ '% ')//Set page progress bar     }    , bindaction: ' #uploadvideo '     , before:function (input) {    //Returns the parameter item, which is the current input DOM object        console.log (' File Crosses ');    }    , Done:function (res) {             //upload succeeded           Console.log (res)     } });

To modify the Ajax method for upload.js files in modules

Submit File        $.ajax ({          url:options.url          , Type:options.method          , Data:formdata          , Contenttype:false           , Processdata:false          , DataType: ' JSON '          , XHR:OPTIONS.XHR (function (e) {///here Var percent= for new additions)                Math.floor ((e.loaded/e.total) *100);//Calculate Percent                options.progress (percent);//callback returns the value           })          , success: Function (res) {            successful++;            Done (index, RES);            Alldone ();          }          , Error:function (e) {             console.log (e)            aborted++;            That.msg (' request upload interface exception ');            Error (index);            Alldone ();          }        });

Background code:

        Public ActionResult uploadfiles (HttpPostedFileBase fileNames) {String path = "";                Less than 20M if (filenames.contentlength > 0 && filenames.contentlength <= 120971520) {                var fileName = Path.getfilename (filenames.filename);                String q_fn = filename.substring (0, Filename.lastindexof ("."));                String h_fn = Filename.substring (Filename.lastindexof ("."));                String newfilename = Q_fn + DateTime.Now.ToString ("Yyyymmddhhmmss") + h_fn;                Path = Path.Combine (Server.MapPath ("/uploadfile/"), NewFileName);                Filenames.saveas (path);                Path = "/uploadfile/" + newfilename;                var relt = new {TC = path};            Return Content (Jsonconvert.serializeobject (Relt));                } else {var relt = new {TC = "Upload file less than 20M"};     Return Content (Jsonconvert.serializeobject (Relt));       }        } 

function to this end!!!


Liezi:

2. Simulate a fake progress bar

80784717

Layui.use ([' Upload ', ' element ', ' layer '], function () {var upload = Layui.upload,element = Layui.element,layer = Layui.layer;var timer;//defines a timer//does not automatically upload Upload.render after the file is selected ({elem: ' #test8 ', url: ' Upload ', Async:false, method        : ' Post ', data: {upgradetype:function () {return $ ("Input[name= ' Upgradetype ']:checked"). Val ();//Additional parameters passed }}, Auto:false, accept: ' file '//Normal file, exts: ' Zip '//Only allow upload of compressed files, field: ' UploadFile ', bindaction: ' #t Est9 ', choose:function (obj) {//The function here is to intercept the upload file name and display var uploadfileinput=$ (". Layui-upload-file"). Val (); var    Uploadfilename=uploadfileinput.split ("\ \"); $ ("#uploadName"). Text (uploadfilename[uploadfilename.length-1]); }, the Before:function (obj) {//obj parameter contains information that is exactly the same as the Choose Callback Layer.load ();//upload Loadingvar n = 0; timer = setinterval (function () {      Randomly generate a progress of less than 95 according to the time, the specific value can be adjusted by itself n = n + math.random () *10|0;    if (n>95) {n = 95;clearinterval (timer);    } element.progress (' demo ', n+ '% ');}, 50+math.random () *100); }, Done: Function (res) {clearinterval (timer); Element.progress (' demo ', ' 100% ');//The progress bar is set to 100%layer.closeall () when successful; Layer.msg (    ' Upload success ');}    , error:function (index, upload) {element.progress (' demo ', ' 0% '); Layer.closeall ();//Close all layers layer.msg (' Upload update package failed '); }});});

  

Reference: https://www.layui.com/doc/modules/upload.html

Layui File upload progress bar (analog)

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.