下面我们使用Html 5的新特性file api实现上传文件,并显示上传文件进度百分比。意图是这样的,当选择文件时,显示当前文件信息。这里我们是结合Asp.net MVC做为服务端,您也可以是其它的服务端语言。让我们看面这个片断的HTML:

    @using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" , id="form1"}))

    {    

        <div class="row">

            <label for="file">

                Upload Image:</label>

            <input type="file" name="fileToUpload" id="fileToUpload"  multiple="multiple" onchange="fileSelected();" />

        </div>

        <div id="fileName">

        </div>

        <div id="fileSize">

        </div>

        <div id="fileType">

        </div> 

        <div class="row">

            <input type="button" onclick="uploadFile()" value="Upload Image" />

        </div>

        <div id="progressNumber">

        </div>

    }

相关的Javascript是这样的:

        function fileSelected() {

            var file = document.getElementById('fileToUpload').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("fileToUpload", document.getElementById('fileToUpload').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.open("POST", "Home/Upload");

            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.");

        }

上面是就原生的Javascript,在onchange事件执行fileSelected的function,在点击button执行了uploadFile的function,这里使用XMLHttpRequest实现ajax上传文件。 注意代码在Firefox 14 可以工作,IE 9目前不支持file api,可以参加这里。 服务端的代码很简单:

    public class HomeController : Controller

    {

        public ActionResult Index()

        {

            return View();

        }

        /// <summary>

        /// Uploads the specified files.

        /// </summary>

        /// <param name="fileToUpload">The files.</param>

        /// <returns>ActionResult</returns>

        [HttpPost]

        public ActionResult Upload(HttpPostedFileBase[] fileToUpload)

        {

            foreach (HttpPostedFileBase file in fileToUpload)

            {

                string path = System.IO.Path.Combine(Server.MapPath("~/App_Data"), System.IO.Path.GetFileName(file.FileName));

                file.SaveAs(path);

            }

            ViewBag.Message = "File(s) uploaded successfully";

            return RedirectToAction("Index");

        }

    }
文章来自:http://www.cnblogs.com/wintersun/archive/2012/08/30/2663408.html
补充:
JS XMLHttpRequest.upload.addEventListener 传参,回调

// 原来 xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.upload.addEventListener("load", function (event) { uploadProgress(event) }, false);

通过event获取文件属性

JSON.parse(event.target.responseText);

例如:xhr.upload.addEventListener("load", function (event) { uploadProgress(JSON.parse(event.target.responseText)) }, false);

HTML5上传文件显示进度的更多相关文章

  1. ajax上传文件显示进度

    下面要做一个ajax上传文件显示进度的操作,文末有演示地址 这里先上代码: 1.前端代码 upload.html <!DOCTYPE html> <html lang="e ...

  2. axios+Vue上传文件显示进度

    一,前言 最近在用Vue,然后上传文件时需要显示进度,于是网上搜了一下,经过自己实测终于也弄明白了 二,效果 三,代码 HTML代码 <div id="app"> &l ...

  3. jQuery上传文件显示进度条

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script sr ...

  4. 【ASP.NET MVC】HTML5+MVC上传文件显示进度

    head> <title>Index</title> <style type="text/css"> #statusBorder { po ...

  5. Asp.Net实现无刷新文件上传并显示进度条(非服务器控件实现)(转)

    Asp.Net实现无刷新文件上传并显示进度条(非服务器控件实现) 相信通过Asp.Net的服务器控件上传文件在简单不过了,通过AjaxToolkit控件实现上传进度也不是什么难事,为什么还要自己辛辛苦 ...

  6. 【原创】用JAVA实现大文件上传及显示进度信息

    用JAVA实现大文件上传及显示进度信息 ---解析HTTP MultiPart协议 (本文提供全部源码下载,请访问 https://github.com/grayprince/UploadBigFil ...

  7. Extjs 使用fileupload插件上传文件 带进度条显示

    一.首先我们看看官方给出的插件的解释: 一个文件上传表单项具有自定义的样式,并且可以控制按钮的文本和 像文本表单的空文本类似的其他特性. 它使用一个隐藏的文件输入元素,并在用户选择文件后 在form提 ...

  8. 不带插件 ,自己写js,实现批量上传文件及进度显示

    今天接受项目中要完成文件批量上传文件而且还要显示上传进度,一开始觉得这个应该不是很麻烦,当我在做的时候遇到了很多问题,很头疼啊. 不过看了别人写的代码,自己也测试过,发现网上好多都存在一些问题,并不是 ...

  9. 文件上传下载显示进度(vue)

    编写了一个vue组件,可以实时显示文件上传和下载时候的进度 <template> <div v-show="circleProgress_wrapper_panel_sta ...

随机推荐

  1. git-ftp代码部署方式

    虽然如今ci方法已经在很多团队使用了,但对于一些个人性的基于PHP的跑在虚拟主机的小项目,既没有服务端的Git环境,又不想时刻跑一个Genkins,就只能回到原始的FTP上传了. 所幸有了git-ft ...

  2. Spring Security 使用数据库用户进行认证

    本文参考或摘录自:http://haohaoxuexi.iteye.com/blog/2157769 本文使用Spring Security自带的方式连接数据库对用户进行认证. 1.Spring Se ...

  3. Java知多少(96)绘图之设置字型和颜色

    Java绘图中,显示文字的方法主要有三种:(1)drawString(String str,int x,int y):在指定的位置显示字符串.(2)drawChars(char data[],int ...

  4. H3C S5120清除console口密码

    1.开机启动交换机显示Press Ctrl-B to enter Extended Boot menu...0  字样迅速按Ctrl-B进入如下字符介面提示: Press Ctrl-B to ente ...

  5. 将Java web应用部署到Tomcat 及部署到Tomcat根目录 的三种方式

    Tomcat作为Servlet/JSP容器(服务器)挺不错的,开源免费,需要知道的是Tomcat是一个Web服务器,其符合Servlet/JSP规范,但是却没有实现所有JavaEE规范,所以我们还是应 ...

  6. laravel5.4中验证与错误提示设置

    1.对于交互提交数据,验证如: #验证 $this->validate(\request(),[ 'title' => 'required|string|min:3|max:20', 'c ...

  7. Ubuntu14.04下安装MATLAB后,通过命令行打开其图形界面

    安装的是Matlab R2017a,使用的是默认安装目录,安装在目录/usr/local/MATLAB/R2017a/bin中.那么安装完成之后系统不会给Matlab添加系统路径,只有把终端切换到安装 ...

  8. vector的多套遍历方案

    1.迭代器 begin,end,*it++ 2.下标法 3.at函数(GetAt) 4.指针法 指针移到头部rewind.

  9. [IR] Dictionary Coding

    [数据压缩]LZ77算法原理及实现 [数据压缩]LZ78算法原理及实现 Lempel–Ziv–Welch 年发表的论文<A Universal Algorithm for Sequential ...

  10. [OpenCV] Samples 16: Decompose and Analyse RGB channels

    物体的颜色特征决定了灰度处理不是万能,对RGB分别处理具有相当的意义. #include <iostream> #include <stdio.h> #include &quo ...