asp.net file upload progress bar implementation code

Source: Internet
Author: User
Tags datetime file upload file upload progress bar httpcontext reserved

ASP tutorial. Net File Upload progress bar implementation code

index.htm is the File upload page, submit form to the Uploadhandler directory default.aspx, to achieve file upload.

Progresshandler directory three files for the ABORT.ASHX, genericguid.ashx,handler.ashx functions are: Based on the GUID to cancel the file is being uploaded, generate a GUID, according to the GUID to obtain upload information.

The first step: to create a index.htm page, this upload page, you need to pay attention to the need for a hidden iframe, and the name of the form submitted by the target.

View Code 1 <!doctype HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/tr/xhtml1/dtd/xhtml1-tr Ansitional.dtd ">


2


3 <html xmlns= "http://www.w3.org/1999/xhtml" >


4 <head>


5 <title>asp.net Tutorial Ajax file Upload progress bar Example </title>


6 <meta name= "author" content= "Li seized the whole"/>


7 <link href= "styles/base.css Tutorial" rel= "stylesheet" type= "Text/css"/>


8 <script src= "Scripts/jquery-1.4.2.min.js" type= "text/Web Effects" ></script>


9 <script src= "Scripts/jquery-ui-1.8.2.custom.min.js" type= "Text/javascript" ></script>


<script src= "Scripts/ljq.lib.js" type= "Text/javascript" ></script>


One <script src= "scripts/ajax/guidget.js" type= "Text/javascript" ></script>


<script src= "Scripts/ajax/ajax-progress-upload.js" type= "Text/javascript" ></script>


</head>


<body>


<div id= "Upload_demo" >


<div class= "title" >asp.net Ajax File Upload progress bar Example </div>


<form action= "uploadhandler/default.aspx" enctype= "Multipart/form-data" method= "post" target= "Upload_hidden_ iframe ">


<input id= "GUID" Name= "GUID" value= "" type= "hidden"/>


<p>* This procedure is suitable for small file uploads, no more than 80mb</p>


<p> file Address </p>


<input name= "Upload_file" type= "file"/>


<br/>


<p> File Description </p>


<textarea name= "Description_file" ></textarea>


<br/>


Num <br/>


<input type= "Submit" value= "Upload file"/>


</form>


</div>


<div id= "Back_panel" ></div>


<div id= "Upload_panel" >


<div id= "Upload_title" > File Upload </div>


<div id= "Upload_content" >


34


<ul>


<li id= "Finished_percent" > is ready to upload ...</li>


Notoginseng <li><div id= "Upload_bar" ><div id= "upload_progress" ></DIV></DIV>&L T;/li>


<li id= "Upload_speed" ></li>


<li id= "Upload_costtime" ></li>


<li id= "Upload_filesize" ></li>


<li id= "Upload_filename" ></li>


</ul>


43


<div id= "Upload_detail" ></div>


<div id= "Upload_choose" >


<span id= "Upload_cancel" > Cancellation </span><span id= "Upload_submit" > OK </span>


</div>


</div>


</div>


<iframe name= "Upload_hidden_iframe" style= "Display:none;" >


51


</iframe>


53


54


</body>


</html>



The second step is to create the Generateguid.ashx file, which is to generate a unique GUID.

View Code

The third step is to create a default.aspx file that uploads the file when submitting the form.

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 Li Inspection full


10 *


* Date 2011-03-10


12 *


Contact me


14 *


Address 18th Liao Xi Road, Dalian Development Zone, Liaoning Province, Dalian Institute of Nationalities, 631 Studio


16 *


* Email lijianquan07@gmail.com


18 *


* QQ 55643287


20 *


* Copyright (c) Li seized all rights reserved


22 *


23 * =======================================================================================


24 */


Partial class Uploadhandler_default:system.web.ui.page


26 {


protected void Page_Load (object sender, EventArgs e)


28 {


The String guid = request.params["GUID"];


Uploadutil utilhelp = new Uploadutil (this, GUID);


Utilhelp.upload ();


32}


33}


Upload Core code:

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 *


* Developed by Li Inspection full


13 *


Date 2011-03-10


15 *


* Contact me


17 *


Address 18th Liao Xi Road, Dalian Development Zone, Liaoning Province, Dalian Institute of Nationalities, 631 Studio


19 *


* Email lijianquan07@gmail.com


21 *


* QQ 55643287


23 *


* Copyright (c) Li rights all the reserved


25 *


26 * =======================================================================================


27 */


public class Uploadutil


29 {


private stream reader;


to private FileStream fstream;


The private const int buffersize = 10000;


The private string FilePath =new page (). Server.MapPath (Configurationmanager.apps tutorial ettings["Upload_folder"));


The private page page;


The private string GUID;


Uploadutil Public (Page page, string guid)


37 {


this.page = page;


This.guid = GUID;


40}


The public void upload ()


42 {


if (This.page.request.files.count > 0)


44 {


This.doupload (This.page.request.files[0]);


46}


Or else


48 {


return;


50}


51}


The private void Doupload (Httppostedfile postedfile)


53 {


BOOL _abort = false;


The string _filepath = This.filepath + datetime.now.tofiletime () + "//";


if (!directory.exists (_filepath))


57 {


Directory.CreateDirectory (_filepath);


59}


A string _filename = Postedfile.filename;


Downloadingfileinfo info = new Downloadingfileinfo (_filename,postedfile.contentlength,postedfile.contenttype);


The object fileobj = Httpcontext.current.cache[this.guid];


if (fileobj!= null)


64 {


Httpcontext.current.cache.remove (THIS.GUID);


66}


Httpcontext.current.cache.add (This.guid, info, NULL, datetime.now.adddays (1), TimeSpan.Zero, CacheItemPriority. AboveNormal, NULL);


DateTime begin=datetime.now.tolocaltime ();


FStream = new FileStream (_filepath+_filename,filemode.create);


reader = Postedfile.inputstream;


(a) byte []buffer=new byte[buffersize];


int len = Reader.read (buffer,0,buffersize);


73


The while (Len > 0&&!_abort)


75 {


Fstream.write (Buffer,0,len);


The DateTime end = Datetime.now.tolocaltime ();


Info.costtime = (long) (end-begin). TotalMilliseconds;


info.filefinished = Len;


80


81//Analog delay use, the actual application when the cancellation of his


Thread.Sleep (10);


83


HTTPCONTEXT.CURRENT.CACHE[THIS.GUID] = info;


_abort= ((downloadingfileinfo) Httpcontext.current.cache[this.guid]). Abort;


Len = Reader.read (buffer,0,buffersize);


87}


88


Reader.close ();


Fstream.close ();


(_abort)


92 {


(File.exists (_filepath + _filename))


94 {


File.delete (_filepath + _filename);


96}


97}


98}


99


100}


The fourth step is to create a handler.ashx file for viewing file uploads.

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 Li Inspection full


10 *


* Date 2011-03-10


12 *


Contact me


14 *


Address 18th Liao Xi Road, Dalian Development Zone, Liaoning Province, Dalian Institute of Nationalities, 631 Studio


16 *


* Email lijianquan07@gmail.com


18 *


* QQ 55643287


20 *


* Copyright (c) Li seized all rights reserved


22 *


23 * =======================================================================================


24 */


The public class Handler:ihttphandler {


26


ProcessRequest void (HttpContext context) {


Context.response.contenttype = "Application/xml";


Context.response.charset = "Utf-8";


String guid = context.request.form["GUID"];


Downloadingfileinfo info = Context.cache[guid] as Downloadingfileinfo;


XDocument doc = new XDocument ();


XElement root = New XElement ("root");


if (info!= null)


35 {


XElement filename = new XElement ("filename", info.filename);


Panax Notoginseng XElement filefinished = new XElement ("filefinished", info.filefinished);


XElement filesize = new XElement ("FileSize", info.filesize);


XElement costtime = new XElement ("Costtime", info.costtime);


XElement filestate = new XElement ("Filestate", info.filestate);


XElement speed = new XElement ("Speed", info.speed);


XElement percent = new XElement ("percent", info.percent);


XElement abort = new XElement ("Abort", false);


Root.add (filename);


Root.add (filefinished);


Root.add (filesize);


Root.add (Costtime);


Root.add (filestate);


Root.add (speed);


Root.add (percent);


Wuyi if (info.abort)


52 {


Abort.value = Info.abort.tostring ();


Context.cache.remove (GUID);


55}


if (Info.filestate = "finished")


57 {


Context.cache.remove (GUID);


59}


60


61


62}


Or else


64 {


XElement none = new XElement ("None", "No File");


Root.add (none);


67}


Doc.add (root);


Context.Response.Write (Doc.tostring ());


Context.response.end ();


71}


72


public bool IsReusable {


get {


return false;


76}


77}


78


79}


The fifth step is to create a abort.ashx file to cancel the upload.

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 Li Inspection full


9 *


* Date 2011-03-10


11 *


* Contact me


13 *


Address 18th Liao Xi Road, Dalian Development Zone, Liaoning Province, Dalian Institute of Nationalities, 631 Studio


15 *


* Email lijianquan07@gmail.com


17 *


* QQ 55643287


19 *


Copyright (c) All rights reserved Lee


21 *


22 * =======================================================================================


23 */


24


The public class Abort:ihttphandler {


26


ProcessRequest void (HttpContext context) {


Context.response.contenttype = "Application/xml";


Context.response.charset = "Utf-8";


String guid = context.request.form["GUID"];


to bool abort = String.IsNullOrEmpty (context.request.form["Abort"])? False:true;


Downloadingfileinfo info = Context.cache[guid] as Downloadingfileinfo;


if (info!= null)


34 {


Info.abort = abort;


CONTEXT.CACHE[GUID] = info;


37}


XDocument doc = new XDocument ();


XElement root = New XElement ("root");


XElement flag = new XElement ("Flag", Info==null?) False ": true");


Root.add (flag);


Doc.add (root);


Context.Response.Write (Doc.tostring ());


Context.response.end ();


45}


46


The public bool IsReusable {


get {


return false;


50}


51}


52


53}



OK, here's the JavaScript script, I'm referencing the jquery framework, and the UI framework.

The core code is the Ajax-progress-upload.js file, plus a file that gets the GUID.

View Code 1/*========================================================================================


2 *


3 * Developed by Li Inspection full


4 *


5 * Date 2011-03-10


6 *


7 * Contact me


8 *


9 * Address, Liaoning Province, Dalian Development Zone, Liaohe West Road, No. 18th, Dalian Institute of Nationalities, second education 631 Studio


10 *


One * Email lijianquan07@gmail.com


12 *


* QQ 55643287


14 *


* Copyright (c) Li seized all rights reserved


16 *


17 * =======================================================================================


18 */


$ (document). Ready (function () {


var _guid_url = "Progresshandler/generateguid.ashx";


var _progress_url = "Progresshandler/handler.ashx";


var _abort_url = "Progresshandler/abort.ashx";


The var _target = "#guid";


var _guid = "";


var _cancel = false;


var _timer;


Ljq.setguid (_target, _guid_url);


$ ("#upload_panel"). Draggable ({handle: "#upload_title"});


$ ("#upload_choose span"). Hover (function () {


$ (this). CSS ({


"Color": "#f6af3a",


"Border": "1px solid #e78f08"


33});


The function () {


$ (this). CSS ({


"Color": "#1c94cd",


Notoginseng "Border": "1px solid #ddd"


38});


39});


$ ("#upload_cancel"). Click (function () {


$.ajax ({


URL: _abort_url,


Data: {GUID: _guid, abort:true},


DataType: "XML",


Type: "Post",


Success:function () {


47


$ ("#upload_panel"). Fadeout (' fast ');


$ ("#back_panel"). fadeout (1000);


Window.clearinterval (_timer);


51}


52});


53


54


55});


$ ("#upload_submit"). Click (function () {


$ ("#upload_panel"). Fadeout (' fast ');


$ ("#back_panel"). Fadeout ("1000");


59});


$ ("form"). Submit (function () {


_guid = $ (_target). Val ();


if ($ ("Input[name= ' Upload_file ']"). val () = "") {


("No upload file specified!") ");


return false;


65}


$ ("#upload_progress"). CSS ("width", "0%");


$ ("#finished_percent"). HTML ("Ready to upload ...");


$ ("#upload_speed"). HTML ("");


$ ("#upload_filename"). HTML ("");


$ ("#upload_filesize"). HTML ("");


$ ("#upload_costtime"). HTML ("");


_option var = {


_progress_url URL:


Data: {GUID: _guid},


DataType: "XML",


Type: "Post",


Beforesend:function () {


$ ("#back_panel"). Fadeto (' fast ', ' 0.5 ');


$ ("#upload_panel"). Fadein (' 1000 ');


80},


Bayi Success:function (response) {


82


($ (response). Find ("root abort"). Text () = = "true") {


$ ("#upload_panel"). Fadeout (' fast ');


$ ("#back_panel"). fadeout (1000);


Window.clearinterval (_timer);


87}


88


The-Else if ($ (response). Find ("root none"). Text () = "No file") {


90


91}


He else {


_percent var = ($ (response). Find ("root percent"). Text () * 100);


_speed var = $ (response). Find ("root speed"). Text ();


The var _filesize = $ (response). Find ("root filesize"). Text ();


var _upload_costtime = $ (response). Find ("root costtime"). Text ();


if (parseint (_speed) < 1024) {


_speed = Ljq.tofix (_speed) + "KB";


} else {


_speed = Ljq.tofix (_speed/1024) + "MB";


101}


102


if (parseint (_filesize)/1024 < 1024) {


_filesize = Ljq.tofix (_filesize/1024) + "KB";


' Else If ' (parseint (_filesize)/1024/1024 < 1024) {


_filesize = Ljq.tofix (_filesize/1024/1024) + "MB";


' Else {


108 _filesize = Ljq.tofix (_filesize/1024/1024/1024) + "GB";


109}


110


if (_upload_costtime < 1000) {


112 _upload_costtime = _upload_costtime + "millisecond";


113} else if (_upload_costtime/1000 < 60) {


114 _upload_costtime = parseint (_upload_costtime/1000) + "seconds" + _upload_costtime% 1000 + "milliseconds";


+} else {


116 _upload_costtime = parseint (_upload_costtime/1000/60) + "min" + parseint (_upload_costtime% 60000)/1000) + "seconds" + _upload_costtime% 1000 + "milliseconds";


117}


118 $ ("#upload_progress"). CSS ("width", parseint (_percent) + "%");


119 $ ("#finished_percent"). HTML ("percent complete:" + ljq.tofix (_percent) + "%");


$ ("#upload_speed"). HTML ("Upload speed:" + _speed + "/sec");


121 $ ("#upload_filename"). HTML ("file name:" + $ (response). FIND ("root filename"). text ());


122 $ ("#upload_filesize"). HTML ("File size:" + _filesize);


123 $ ("#upload_costtime"). html ("Upload time consuming:" + _upload_costtime);


124 if (_percent >= 100) {


125


126 Window.clearinterval (_timer);


127 $ ("#finished_percent"). HTML ("<span style= ' color:green; ') > File Upload complete </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 Li Inspection full


4 *


5 * Date 2011-03-10


6 *


7 * Contact me


8 *


9 * Address, Liaoning Province, Dalian Development Zone, Liaohe West Road, No. 18th, Dalian Institute of Nationalities, second education 631 Studio


10 *


One * Email lijianquan07@gmail.com


12 *


* QQ 55643287


14 *


* Copyright (c) Li seized all rights reserved


16 *


17 * =======================================================================================


18 */


(function () {


if (!window[' LJQ ']) {


window[' ljq '] = {};


22}


SetGuid function (target, URL) {


var _option = {


Url:url,


DataType: "XML",


Type: "Post",


Success:function (response) {


$ (target). Val ($ (response). Find ("root GUID"). text ());


30}


31};


$.ajax (_option);


33}


window[' ljq ' [' setguid '] = setguid;


The function getprogress (GUID) {


var _option = {};


37}


38}) ();

All right

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.