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);
            }
        }
  • 相关阅读:
    C# using的三种用法
    C# 匿名方法和Lambda表达式
    c#中内置委托
    c#委托中的匿名方法和lambda表达式
    java生成条形码
    根据日期筛选和模糊查询
    mysql中ifnull()方法的用法
    mysql数据库中的出发器
    动态SQL之<where>、<if>条件判断
    动态sql
  • 原文地址:https://www.cnblogs.com/raorao1994/p/10188912.html
Copyright © 2011-2022 走看看