• HTML5_纯JS实现上传文件显示文件大小,文件信息,上传进度_不使用JS库


    前台 html
    <input type="file" id="_netLogo" onchange="fileSelected();">
    <div id="fileName">
    </div>
    <div id="fileSize">
    </div>
    <div id="fileType">
    </div>
    <div id="progressNumber">
    </div>
    <button type="button" class="btn btn-default" onclick="uploadFile()">上传</button>

    前台JS

    <script type="text/javascript">

    function fileSelected() {
    var file = document.getElementById('_netLogo').files[0];
    if (file) {
    var fileSize = 0;
    if (file.size > 1024 * 1024)
    fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
    else
    fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';

    document.getElementById('fileName').innerHTML = 'Name: ' + file.name;
    document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
    document.getElementById('fileType').innerHTML = 'Type: ' + file.type;
    }
    }

    function uploadFile() {
    var fd = new FormData();
    fd.append("_netLogo", document.getElementById('_netLogo').files[0]);
    var xhr = new XMLHttpRequest();
    xhr.upload.addEventListener("progress", uploadProgress, false);
    xhr.addEventListener("load", uploadComplete, false);
    xhr.addEventListener("error", uploadFailed, false);
    xhr.addEventListener("abort", uploadCanceled, false);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.open("POST", "/User/WNetEdit2_test");
    xhr.send(fd);
    }

    function uploadProgress(evt) {
    if (evt.lengthComputable) {
    var percentComplete = Math.round(evt.loaded * 100 / evt.total);
    document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
    }
    else {
    document.getElementById('progressNumber').innerHTML = 'unable to compute';
    }
    }

    function uploadComplete(evt) {
    /* This event is raised when the server send back a response */
    alert(evt.target.responseText);
    }

    function uploadFailed(evt) {
    alert("There was an error attempting to upload the file.");
    }

    function uploadCanceled(evt) {
    alert("The upload has been canceled by the user or the browser dropped the connection.");
    }
    </script>

    后台 测试函数

    public string WNetEdit2_test()
    {
    var f = Request.Files[0];
    string path = System.IO.Path.Combine(Server.MapPath("~/App_Data"), System.IO.Path.GetFileName(f.FileName));
    f.SaveAs(path);
    return "File(s) uploaded successfully";
    }

  • 相关阅读:
    PHP UPLOAD 实现附件上传
    迁移服务器小记
    php TP5.1 将session 存入Redis
    js 精度问题的处理方法
    Aspect 浏览器插件
    JavaScript 构建工具 的发展和变化
    js input 保留1位小数
    如何使用adb 安装 apk应用
    php精度计算问题
    [Typescript] 89. Hard Currying 1
  • 原文地址:https://www.cnblogs.com/90nice/p/4080307.html
Copyright © 2020-2023  润新知