zoukankan      html  css  js  c++  java
  • 异步上传文件

     /*
        *异步上传文件
        *option参数
        **url:上传路径
        **data:上传的其他数据{id:"1"}
        **maxSize:文件最大值(单位M)
        **callback:回调函数(可空)
        **beforeSend:上传前函数(可空)
        */
        function Upload(option) {
            var fd = new FormData(),
                xhr = new XMLHttpRequest(),
                input;
            if (document.getElementById('_RobinUploadInput')) {
                input = document.getElementById('_RobinUploadInput');
            } else {
                input = document.createElement('input');
                input.setAttribute('id', '_RobinUploadInput');
                input.setAttribute('type', 'file');
                input.setAttribute('name', 'file');
                document.body.appendChild(input);
                input.style.display = 'none';
            }
            input.click();
            input.onchange = function () {
                if (!input.value) { return; }
                if (option.maxSize && input.files[0].size > option.maxSize * 1024 * 1024) {
                    alert("请上传小于' + option.maxSize + 'M的文件");
                    return;
                }
                if (option.beforeSend instanceof Function) {
                    if (option.beforeSend(input) === false) {
                        return false;
                    }
                }
                if (option.data) {
                    for (var name in option.data) {
                        fd.append(name, option.data[name]);
                    }
                }
                fd.append('Filedata', input.files[0]);
                xhr.open('post', option.url);
                xhr.onreadystatechange = function () {
                    if (xhr.status == 200) {
                        if (xhr.readyState == 4) {
                            if (option.callback instanceof Function) {
                                option.callback(xhr.responseText);
                            }
                        }
                    } else {
                        alert("上传失败");
                    }
                }
                xhr.upload.onprogress = function (event) {
                    var pre = Math.floor(100 * event.loaded / event.total);
                    if (option.uploading instanceof Function) {
                        option.uploading(pre);
                    }
                }
                xhr.send(fd);
            }
        }
  • 相关阅读:
    Codeforces 1265A Beautiful String
    1039 Course List for Student (25)
    1038 Recover the Smallest Number (30)
    1037 Magic Coupon (25)
    1024 Palindromic Number (25)
    1051 Pop Sequence (25)
    1019 General Palindromic Number (20)
    1031 Hello World for U (20)
    1012 The Best Rank (25)
    1011 World Cup Betting (20)
  • 原文地址:https://www.cnblogs.com/raorao1994/p/10188912.html
Copyright © 2011-2022 走看看