Asp.net single file upload solution with progress bar, asp.net progress bar

Source: Internet
Author: User
Tags file upload progress bar

Asp.net single file upload solution with progress bar, asp.net progress bar

Recently, I encountered many problems in my project, such as uploading files with progress bars. I have read a lot of online documents and have not found ASP in the true sense. NET implementation progress bar upload (maybe I did not find it). Next I will share with you the program I implemented.
First, let's take a look at the interface effect. Of course, you can completely modify the interface for your own use.

First, let's explain this program. This program uses the jquery framework to implement small file upload, which cannot exceed 80 Mb. configure the configuration in the config file, but there is a maximum value. For details, see msdn. The development environment uses visual studio 2013. net framework 4.5. when running the program, check whether the requirements are met.
Let's take a look at the implementation principles. Basic principle: upload a file on one page, and listen on how many files are uploaded on the other page.
There are two things to explain: first, how do I know that the listened file is the uploaded file? The implementation mechanism is simple, that is, to generate a unique guid for asp.net. This id serial number is unique and assigned to a hidden field through ajax. The second, how do I obtain the file information of the guid mark? Through the asp.net cache mechanism, the upload information is constantly written into the Cache during the upload process until the file upload is complete, and the cached information is obtained through another guid, the information includes the information you want, such as how many bytes are uploaded and how long it takes. Okay. Let's explain it here. If you have any questions, leave a message.
The specific implementation is as follows:
The file directory structure is as follows:

 

Index.htm is the file upload page. submit the form to Default. aspx under the UploadHandler directory to upload the file.
The three files in the ProgressHandler directory are Abort. ashx, GenericGuid. ashx, and Handler. ashx. The functions are as follows: cancel the files being uploaded Based on the Guid, generate a Guid, and obtain the upload information based on the Guid.
Step 1: Create an index.htm page. When uploading this page, you must note that you need a hidden iframe and its name is the target submitted by form.

<! Doctype html public "-// W3C // dtd xhtml 1.0 Transitional // EN "" http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> <Html xmlns =" http://www.w3.org/1999/xhtml "> <Head> <title> ASP. NET Ajax File Upload progress bar example </title> <meta name = "author" content = ""/> <link href = "Styles/base.css" rel = "stylesheet" type = "text/css"/> <script src = "Scripts/jquery-1.4.2.min.js" type = "text/javascript"> </script> <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> <script src =" Scripts/Ajax/GuidGet. js "type =" text/javascript "> </script> <script src =" Scripts/Ajax/ajax-progress-upload.js "type =" text/javascript "> </script> 

Step 2: Create the GenerateGuid. ashx file to generate a unique Guid.

<% @ WebHandler Language = "C #" Class = "ProgressHandler. handler "%> using System; using System. web; using System. xml. linq; namespace ProgressHandler {public class Handler: IHttpHandler {// <summary> // obtain the GUID of the uploaded file. /// </summary> /// <param name = "context"> current request entity </param> /// <creattime> 2015-06-28 </creattime> // <author> FreshMan </author> public void ProcessRequest (HttpContext context) {context. response. charset = "UTF-8"; context. response. contentType = "application/xml"; var guid = Guid. newGuid (). toString (); var doc = new XDocument (); var root = new XElement ("root"); var xGuid = new XElement ("guid", guid); root. add (xGuid); doc. add (root); context. response. write (doc. toString (); context. response. end () ;}public bool IsReusable {get {return false ;}}}}

Step 3: Create the Default. aspx file to upload the file when submitting the form.

using System;  namespace UploadHandler {  public partial class UploadHandlerDefault : System.Web.UI.Page  {   protected void Page_Load(object sender, EventArgs e)   {    string guid = Request.Params["guid"];    UploadUtil utilHelp = new UploadUtil(this, guid);    utilHelp.Upload();   }  } } 

Upload the core code:

Using System; using System. web; using System. IO; using System. configuration; using System. web. UI; using System. web. caching; using System. threading; public class UploadUtil {private Stream _ reader; private FileStream _ fStream; private const int Buffersize = 10000; private readonly string _ filePath = new Page (). server. mapPath (ConfigurationManager. appSettings ["upload_folder"]); private readonly Page _ Page; private readonly string _ guid; public UploadUtil (Page page, string guid) {_ page = page; _ guid = guid;} public void Upload () {if (_ page. request. files. count> 0) {DoUpload (_ page. request. files [0]) ;}} private void DoUpload (HttpPostedFile postedFile) {bool abort = false; string uploadFilePath = _ filePath + DateTime. now. toFileTime () + "//"; if (! Directory. exists (uploadFilePath) {Directory. createDirectory (uploadFilePath);} string uploadFileName = postedFile. fileName; DownloadingFileInfo info = new DownloadingFileInfo (uploadFileName, postedFile. contentLength, postedFile. contentType); object fileObj = HttpContext. current. cache [_ guid]; if (fileObj! = Null) {HttpContext. current. cache. remove (_ guid);} HttpContext. current. cache. add (_ guid, info, null, DateTime. now. addDays (1), TimeSpan. zero, CacheItemPriority. aboveNormal, null); DateTime begin = DateTime. now. toLocalTime (); _ fStream = new FileStream (uploadFilePath + uploadFileName, FileMode. create); _ reader = postedFile. inputStream; byte [] buffer = new byte [Buffersize]; int len = _ reader. read (buffer, 0, Buffersize); while (len> 0 &&! Abort) {_ fStream. write (buffer, 0, len); DateTime end = DateTime. now. toLocalTime (); info. costTime = (long) (end-begin ). totalMilliseconds; info. fileFinished + = len; // simulate the delay. in actual application, cancel the Thread. sleep (1000); HttpContext. current. cache [_ guid] = info; abort = (DownloadingFileInfo) HttpContext. current. cache [_ guid]). abort; len = _ reader. read (buffer, 0, Buffersize);} _ reader. close (); _ fStream. close (); if (abort) {if (File. exists (uploadFilePath + uploadFileName) {File. delete (uploadFilePath + uploadFileName );}}}}

 

Step 4: Create the Handler. ashx file to view the file upload status.

<% @ WebHandler Language = "C #" Class = "ProgressHandler. handler "%> using System. web; using System. xml. linq; namespace ProgressHandler {public class Handler: IHttpHandler {// <summary> // obtain the progress of the file to be uploaded /// </summary> /// <param name = "context"> current request entity </param> /// <creattime> 2015-06-28 </creattime> // <author> FreshMan </author> public void ProcessRequest (HttpContext context) {context. response. contentType = "Application/xml"; context. response. charset = "UTF-8"; var guid = context. request. form ["guid"]; var info = context. cache [guid] as DownloadingFileInfo; var doc = new XDocument (); var root = new XElement ("root"); if (info! = Null) {var fileName = new XElement ("fileName", info. fileName); var fileFinished = new XElement ("fileFinished", info. fileFinished); var fileSize = new XElement ("fileSize", info. fileSize); var costTime = new XElement ("costTime", info. costTime); var fileState = new XElement ("fileState", info. fileState); var speed = new XElement ("speed", info. speed); var percent = new XElement ("percent", info. percent); var 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); if (info. abort) {abort. value = info. abort. toString (); context. cache. remove (guid);} if (info. fileState = "finished") {context. cache. remove (guid) ;}} else {var none = new XElement ("none", "no file"); root. add (none);} doc. add (root); context. response. write (doc. toString (); context. response. end () ;}public bool IsReusable {get {return false ;}}}}

Step 5: Create the Abort. ashx file to cancel the upload.

<% @ WebHandler Language = "C #" Class = "ProgressHandler. abort "%> using System. web; using System. xml. linq; namespace ProgressHandler {public class Abort: IHttpHandler {// <summary> // cancel the upload handler // </summary> // <param name = "context"> current request entity </param> /// <creattime> 2015-06-28 </creattime> // <author> FreshMan </author> public void ProcessRequest (HttpContext context) {context. response. contentType =" Pplication/xml "; context. Response. Charset =" UTF-8 "; var guid = context. Request. Form [" guid "]; var abort =! String. IsNullOrEmpty (context. Request. Form ["abort"]); var info = context. Cache [guid] as DownloadingFileInfo; if (info! = Null) {info. abort = abort; context. cache [guid] = info;} var doc = new XDocument (); var root = new XElement ("root"); var flag = new XElement ("flag ", info = null? "False": "true"); root. add (flag); doc. add (root); context. response. write (doc. toString (); context. response. end () ;}public bool IsReusable {get {return false ;}}}}

Now, we have written javascript scripts. I have referenced the jquery framework and used the ui framework.
The core code is the ajax-progress-upload.js file, and there is also a file that gets the guid.

$ (Document ). ready (function () {var _ guid_url = "ProgressHandler/GenerateGuid. ashx "; var _ progress_url =" ProgressHandler/Handler. ashx "; var _ abort_url =" ProgressHandler/Abort. ashx "; 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"}) ;}, function () {functions (this(.css ({"color ": "# 1c94cd", "border": "1px solid # ddd"}) ;}; $ ("# upload_cancel "). click (function () {$. ajax ({url: _ abort_url, data: {guid: _ guid, abort: true}, dataType: "xml", type: "post", success: function () {$ ("# upload_panel "). fadeOut ('fast '); $ ("# back_panel "). fadeouts (1000); window. clearInterval (_ timer ); }) ;}); $ ("# Upload_submit "). click (function () {$ ("# upload_panel "). fadeOut ('fast '); $ ("# back_panel "). fadeOut ("1000") ;}); $ ("form "). submit (function () {_ guid = $ (_ target ). val (); if ($ ("input [name = 'upload _ file']"). val () = "") {alert ("File Upload not specified! "); Return false ;}$ (" # upload_progress "width .css (" width "," 0% "); $ (" # finished_percent ").html (" prepare for upload... "); $ (" # upload_speed ").html (" "); $ (" # upload_fileName ").html (" "); $ (" # upload_fileSize ").html (""); $ ("# upload_costTime" ).html (""); var _ option = {url: _ progress_url, data: {guid: _ guid}, dataType: "xml", type: "post", beforeSend: function () {$ ("# back_panel "). fadeTo ('fast ', '0. 5 '); $ ("# upload_panel "). fadeIn ('20140901');}, success: function (response) {if ($ (response ). find ("root abort "). text () = "true") {$ ("# upload_panel "). fadeOut ('fast '); $ ("# back_panel "). fadeouts (1000); window. clearInterval (_ timer);} else if ($ (response ). find ("root none "). text () = "no file") {} else {var _ percent = ($ (response ). find ("root percent "). text () * 100); var _ speed = $ (response ). find ("root speed "). text (); 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";} 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 {_ fileSize = LJQ. toFix (_ fileSize/1024/1024/1024) + "Gb";} if (_ upload_costTime <1000) {_ upload_costTime = _ upload_costTime + "millisecond ";} else if (_ upload_costTime/1000 <60) {_ upload_costTime = parseInt (_ upload_costTime/1000) + "second" + _ upload_costTime % 1000 + "millisecond ";} else {_ upload_costTime = parseInt (_ upload_costTime/1000/60) + "Minute" + parseInt (_ upload_costTime % 60000)/1000) + "seconds" + _ upload_costTime % 1000 + "millisecond" ;}$ ("# upload_progress" width .css ("width", parseInt (_ percent) + "% "); $ ("# finished_percent" percent .html ("percent finished:" + LJQ. toFix (_ percent) + "%"); $ ("# upload_speed" ).html ("upload speed:" + _ speed + "/sec "); $ ("# upload_fileName" ).html ("file name:" + $ (response ). find ("root fileName "). text (); $ ("# upload_fileSize" ).html ("file size:" + _ fileSize); $ ("# upload_costTime" ).html ("Upload time: "+ _ upload_costTime); if (_ percent >=100) {window. clearInterval (_ timer); $ ("# finished_percent" pai.html ("<span style = 'color: green; '> File Uploaded </span> ");} if (_ cancel) {window. clearInterval (_ timer) ;}}, error: function () {}}; _ timer = window. setInterval (function () {$. ajax (_ option) ;}, 1000 );});});

The above is the main part of the code. A single asp.net file is uploaded with a progress bar. It does not belong to a task control or flash upload. It is completely uploaded using asp.net, js, or css. If the source code is a development test version, you need to modify the configuration file.

Please click here to download the project source code: http://xiazai.jb51.net/201509/yuanma/asp_net_progressbar (jb51.netw..rar

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.