asp教程.net 文件上传进度条实现代码
index.htm就是文件上传页面,提交form给uploadhandler目录下的default.aspx,以实现文件上传。
progresshandler目录下三个文件为abort.ashx、genericguid.ashx,handler.ashx功能分别为:根据guid取消正在上传的文件,生成guid,根据guid获取上传信息。
第一步:建立index.htm页面,这个上传页面,需要注意的就是需要一个隐藏的iframe,并且名字为form提交的目标。
view code 1 <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
2
3 <html xmlns="http://www.w3.org/1999/xhtml">
4 <head>
5 <title>asp.net教程 ajax文件上传进度条示例</title>
6 <meta name="author" content="李检全" />
7 <link href="styles/base.css教程" rel="stylesheet" type="text/css" />
8 <script src="scripts/jquery-1.4.2.min.js" type="text/网页特效"></script>
9 <script src="scripts/jquery-ui-1.8.2.custom.min.js" type="text/javascript"></script>
10 <script src="scripts/ljq.lib.js" type="text/javascript"></script>
11 <script src="scripts/ajax/guidget.js" type="text/javascript"></script>
12 <script src="scripts/ajax/ajax-progress-upload.js" type="text/javascript"></script>
13 </head>
14 <body>
15 <div id="upload_demo">
16 <div class="title">asp.net ajax 文件上传进度条示例</div>
17 <form action="uploadhandler/default.aspx" enctype="multipart/form-data" method="post" target="upload_hidden_iframe">
18 <input id="guid" name="guid" value="" type="hidden"/>
19 <p>*本程序适合小文件上传,不超过80mb</p>
20 <p>文件地址</p>
21 <input name="upload_file" type="file" />
22 <br />
23 <p>文件描述</p>
24 <textarea name="description_file" ></textarea>
25 <br />
26 <br />
27 <input type="submit" value="上传文件"/>
28 </form>
29 </div>
30 <div id="back_panel"></div>
31 <div id="upload_panel">
32 <div id="upload_title">文件上传</div>
33 <div id="upload_content">
34
35 <ul>
36 <li id="finished_percent">正在准备上传...</li>
37 <li><div id="upload_bar"><div id="upload_progress"></div></div></li>
38 <li id="upload_speed"></li>
39 <li id="upload_costtime"></li>
40 <li id="upload_filesize"></li>
41 <li id="upload_filename"></li>
42 </ul>
43
44 <div id="upload_detail"></div>
45 <div id="upload_choose">
46 <span id="upload_cancel">取消</span><span id="upload_submit">确定</span>
47 </div>
48 </div>
49 </div>
50 <iframe name="upload_hidden_iframe" style="display:none;">
51
52 </iframe>
53
54
55 </body>
56 </html>
第二步,创建generateguid.ashx文件,作用就是生成唯一的guid.
view code
第三步,创建default.aspx文件,用于提交表单时上传文件。
view code 1 using system;
2 using system.collections.generic;
3 using system.linq;
4 using system.web;
5 using system.web.ui;
6 using system.web.ui.webcontrols;
7 /*========================================================================================
8 *
9 * developed by 李检全
10 *
11 * date 2011-03-10
12 *
13 * contact me
14 *
15 * address 辽宁省大连市开发区辽河西路18号大连民族学院二教631工作室
16 *
17 * email lijianquan07@gmail.com
18 *
19 * qq 55643287
20 *
21 * copyright (c) 李检全 all rights reserved
22 *
23 * =======================================================================================
24 */
25 public partial class uploadhandler_default : system.web.ui.page
26 {
27 protected void page_load(object sender, eventargs e)
28 {
29 string guid = request.params["guid"];
30 uploadutil utilhelp = new uploadutil(this, guid);
31 utilhelp.upload();
32 }
33 }
上传核心代码:
view code 1 using system;
2 using system.collections.generic;
3 using system.linq;
4 using system.web;
5 using system.io;
6 using system.configuration;
7 using system.web.ui;
8 using system.web.caching;
9 using system.threading;
10 /*========================================================================================
11 *
12 * developed by 李检全
13 *
14 * date 2011-03-10
15 *
16 * contact me
17 *
18 * address 辽宁省大连市开发区辽河西路18号大连民族学院二教631工作室
19 *
20 * email lijianquan07@gmail.com
21 *
22 * qq 55643287
23 *
24 * copyright (c) 李检全 all rights reserved
25 *
26 * =======================================================================================
27 */
28 public class uploadutil
29 {
30 private stream reader;
31 private filestream fstream;
32 private const int buffersize = 10000;
33 private string filepath =new page().server.mappath(configurationmanager.apps教程ettings["upload_folder"]);
34 private page page;
35 private string guid;
36 public uploadutil(page page, string guid)
37 {
38 this.page = page;
39 this.guid = guid;
40 }
41 public void upload()
42 {
43 if (this.page.request.files.count > 0)
44 {
45 this.doupload(this.page.request.files[0]);
46 }
47 else
48 {
49 return;
50 }
51 }
52 private void doupload(httppostedfile postedfile)
53 {
54 bool _abort = false;
55 string _filepath = this.filepath + datetime.now.tofiletime()+"//";
56 if (!directory.exists(_filepath))
57 {
58 directory.createdirectory(_filepath);
59 }
60 string _filename = postedfile.filename;
61 downloadingfileinfo info = new downloadingfileinfo(_filename,postedfile.contentlength,postedfile.contenttype);
62 object fileobj = httpcontext.current.cache[this.guid];
63 if (fileobj != null)
64 {
65 httpcontext.current.cache.remove(this.guid);
66 }
67 httpcontext.current.cache.add(this.guid, info, null, datetime.now.adddays(1), timespan.zero, cacheitempriority.abovenormal, null);
68 datetime begin=datetime.now.tolocaltime();
69 fstream = new filestream(_filepath+_filename,filemode.create);
70 reader = postedfile.inputstream;
71 byte []buffer=new byte[buffersize];
72 int len = reader.read(buffer,0,buffersize);
73
74 while (len > 0&&!_abort)
75 {
76 fstream.write(buffer,0,len);
77 datetime end = datetime.now.tolocaltime();
78 info.costtime = (long)(end - begin).totalmilliseconds;
79 info.filefinished += len;
80
81 //模拟延时用,实际应用的时候注销他
82 thread.sleep(10);
83
84 httpcontext.current.cache[this.guid] = info;
85 _abort=((downloadingfileinfo)httpcontext.current.cache[this.guid]).abort;
86 len = reader.read(buffer,0,buffersize);
87 }
88
89 reader.close();
90 fstream.close();
91 if (_abort)
92 {
93 if (file.exists(_filepath + _filename))
94 {
95 file.delete(_filepath + _filename);
96 }
97 }
98 }
99
100 }
第四步,创建handler.ashx文件,用于查看文件上传情况。
view code 1 <%@ webhandler language="c#" class="handler" %>
2
3 using system;
4 using system.web;
5 using system.xml.linq;
6 using system.web.caching;
7 /*========================================================================================
8 *
9 * developed by 李检全
10 *
11 * date 2011-03-10
12 *
13 * contact me
14 *
15 * address 辽宁省大连市开发区辽河西路18号大连民族学院二教631工作室
16 *
17 * email lijianquan07@gmail.com
18 *
19 * qq 55643287
20 *
21 * copyright (c) 李检全 all rights reserved
22 *
23 * =======================================================================================
24 */
25 public class handler : ihttphandler {
26
27 public void processrequest (httpcontext context) {
28 context.response.contenttype = "application/xml";
29 context.response.charset = "utf-8";
30 string guid = context.request.form["guid"];
31 downloadingfileinfo info = context.cache[guid] as downloadingfileinfo;
32 xdocument doc = new xdocument();
33 xelement root = new xelement("root");
34 if (info != null)
35 {
36 xelement filename = new xelement("filename", info.filename);
37 xelement filefinished = new xelement("filefinished", info.filefinished);
38 xelement filesize = new xelement("filesize", info.filesize);
39 xelement costtime = new xelement("costtime", info.costtime);
40 xelement filestate = new xelement("filestate", info.filestate);
41 xelement speed = new xelement("speed",info.speed);
42 xelement percent = new xelement("percent",info.percent);
43 xelement abort = new xelement("abort",false);
44 root.add(filename);
45 root.add(filefinished);
46 root.add(filesize);
47 root.add(costtime);
48 root.add(filestate);
49 root.add(speed);
50 root.add(percent);
51 if (info.abort)
52 {
53 abort.value = info.abort.tostring();
54 context.cache.remove(guid);
55 }
56 if (info.filestate == "finished")
57 {
58 context.cache.remove(guid);
59 }
60
61
62 }
63 else
64 {
65 xelement none = new xelement("none","no file");
66 root.add(none);
67 }
68 doc.add(root);
69 context.response.write(doc.tostring());
70 context.response.end();
71 }
72
73 public bool isreusable {
74 get {
75 return false;
76 }
77 }
78
79 }
第五步,创建abort.ashx文件,用于取消上传。
view code 1 <%@ webhandler language="c#" class="abort" %>
2
3 using system;
4 using system.web;
5 using system.xml.linq;
6 /*========================================================================================
7 *
8 * developed by 李检全
9 *
10 * date 2011-03-10
11 *
12 * contact me
13 *
14 * address 辽宁省大连市开发区辽河西路18号大连民族学院二教631工作室
15 *
16 * email lijianquan07@gmail.com
17 *
18 * qq 55643287
19 *
20 * copyright (c) 李检全 all rights reserved
21 *
22 * =======================================================================================
23 */
24
25 public class abort : ihttphandler {
26
27 public void processrequest (httpcontext context) {
28 context.response.contenttype = "application/xml";
29 context.response.charset = "utf-8";
30 string guid = context.request.form["guid"];
31 bool abort = string.isnullorempty(context.request.form["abort"]) ? false : true;
32 downloadingfileinfo info = context.cache[guid] as downloadingfileinfo;
33 if (info != null)
34 {
35 info.abort = abort;
36 context.cache[guid] = info;
37 }
38 xdocument doc = new xdocument();
39 xelement root = new xelement("root");
40 xelement flag = new xelement("flag",info==null?"false":"true");
41 root.add(flag);
42 doc.add(root);
43 context.response.write(doc.tostring());
44 context.response.end();
45 }
46
47 public bool isreusable {
48 get {
49 return false;
50 }
51 }
52
53 }
好了,下面就是编写javascript脚本了,我引用了jquery这个框架,另外还用了ui框架。
核心代码是ajax-progress-upload.js文件,另外还有一个获取guid的文件。
view code 1 /*========================================================================================
2 *
3 * developed by 李检全
4 *
5 * date 2011-03-10
6 *
7 * contact me
8 *
9 * address 辽宁省大连市开发区辽河西路18号大连民族学院二教631工作室
10 *
11 * email lijianquan07@gmail.com
12 *
13 * qq 55643287
14 *
15 * copyright (c) 李检全 all rights reserved
16 *
17 * =======================================================================================
18 */
19 $(document).ready(function () {
20 var _guid_url = "progresshandler/generateguid.ashx";
21 var _progress_url = "progresshandler/handler.ashx";
22 var _abort_url = "progresshandler/abort.ashx";
23 var _target = "#guid";
24 var _guid = "";
25 var _cancel = false;
26 var _timer;
27 ljq.setguid(_target, _guid_url);
28 $("#upload_panel").draggable({ handle: "#upload_title" });
29 $("#upload_choose span").hover(function () {
30 $(this).css({
31 "color": "#f6af3a",
32 "border": "1px solid #e78f08"
33 });
34 }, function () {
35 $(this).css({
36 "color": "#1c94cd",
37 "border": "1px solid #ddd"
38 });
39 });
40 $("#upload_cancel").click(function () {
41 $.ajax({
42 url: _abort_url,
43 data: { guid: _guid, abort: true },
44 datatype: "xml",
45 type: "post",
46 success: function () {
47
48 $("#upload_panel").fadeout('fast');
49 $("#back_panel").fadeout(1000);
50 window.clearinterval(_timer);
51 }
52 });
53
54
55 });
56 $("#upload_submit").click(function () {
57 $("#upload_panel").fadeout('fast');
58 $("#back_panel").fadeout("1000");
59 });
60 $("form").submit(function () {
61 _guid = $(_target).val();
62 if ($("input[name='upload_file']").val() == "") {
63 alert("未指定上传文件!");
64 return false;
65 }
66 $("#upload_progress").css("width", "0%");
67 $("#finished_percent").html("准备上传...");
68 $("#upload_speed").html("");
69 $("#upload_filename").html("");
70 $("#upload_filesize").html("");
71 $("#upload_costtime").html("");
72 var _option = {
73 url: _progress_url,
74 data: { guid: _guid },
75 datatype: "xml",
76 type: "post",
77 beforesend: function () {
78 $("#back_panel").fadeto('fast', '0.5');
79 $("#upload_panel").fadein('1000');
80 },
81 success: function (response) {
82
83 if ($(response).find("root abort").text() == "true") {
84 $("#upload_panel").fadeout('fast');
85 $("#back_panel").fadeout(1000);
86 window.clearinterval(_timer);
87 }
88
89 else if ($(response).find("root none").text() == "no file") {
90
91 }
92 else {
93 var _percent = ($(response).find("root percent").text() * 100);
94 var _speed = $(response).find("root speed").text();
95 var _filesize = $(response).find("root filesize").text();
96 var _upload_costtime = $(response).find("root costtime").text();
97 if (parseint(_speed) < 1024) {
98 _speed = ljq.tofix(_speed) + "kb";
99 } else {
100 _speed = ljq.tofix(_speed / 1024) + "mb";
101 }
102
103 if (parseint(_filesize) / 1024 < 1024) {
104 _filesize = ljq.tofix(_filesize / 1024) + "kb";
105 } else if (parseint(_filesize) / 1024 / 1024 < 1024) {
106 _filesize = ljq.tofix(_filesize / 1024 / 1024) + "mb";
107 } else {
108 _filesize = ljq.tofix(_filesize / 1024 / 1024 / 1024) + "gb";
109 }
110
111 if (_upload_costtime < 1000) {
112 _upload_costtime = _upload_costtime + "毫秒";
113 } else if (_upload_costtime / 1000 < 60) {
114 _upload_costtime = parseint(_upload_costtime / 1000) + "秒" + _upload_costtime % 1000 + "毫秒";
115 } else {
116 _upload_costtime = parseint(_upload_costtime / 1000 / 60) + "分" + parseint((_upload_costtime % 60000) / 1000) + "秒" + _upload_costtime % 1000 + "毫秒";
117 }
118 $("#upload_progress").css("width", parseint(_percent) + "%");
119 $("#finished_percent").html("完成百分比:" + ljq.tofix(_percent) + "%");
120 $("#upload_speed").html("上传速度:" + _speed + "/sec");
121 $("#upload_filename").html("文件名称:" + $(response).find("root filename").text());
122 $("#upload_filesize").html("文件大小:" + _filesize);
123 $("#upload_costtime").html("上传耗时:" + _upload_costtime);
124 if (_percent >= 100) {
125
126 window.clearinterval(_timer);
127 $("#finished_percent").html("<span style='color:green;'>文件上传完成</span>");
128 }
129 if (_cancel) {
130 window.clearinterval(_timer);
131 }
132 }
133
134 },
135 error: function () { }
136 };
137
138 _timer = window.setinterval(function () { $.ajax(_option); }, 1000);
139
140 });
141
142 });
view code 1 /*========================================================================================
2 *
3 * developed by 李检全
4 *
5 * date 2011-03-10
6 *
7 * contact me
8 *
9 * address 辽宁省大连市开发区辽河西路18号大连民族学院二教631工作室
10 *
11 * email lijianquan07@gmail.com
12 *
13 * qq 55643287
14 *
15 * copyright (c) 李检全 all rights reserved
16 *
17 * =======================================================================================
18 */
19 (function () {
20 if (!window['ljq']) {
21 window['ljq'] = {};
22 }
23 function setguid(target, url) {
24 var _option = {
25 url: url,
26 datatype: "xml",
27 type: "post",
28 success: function (response) {
29 $(target).val($(response).find("root guid").text());
30 }
31 };
32 $.ajax(_option);
33 }
34 window['ljq']['setguid'] = setguid;
35 function getprogress(guid) {
36 var _option = {};
37 }
38 })();
好了