asp.net single file with progress bar uploaded solution _ Practical Tips

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

Recently do project encountered many problems, such as file upload with progress bar, see a lot of information on the Internet has not found a real sense of asp.net implementation progress bar upload (may be I did not find), I would like to share with you the implementation of this program.
First look at the interface effect, of course you can completely modify the interface for your own use.

First explain this program, the program uses the jquery framework, the implementation of small file upload, no more than 80Mb, you can in the Web.config file for the corresponding configuration, but there is a maximum value, the specific need to view MSDN. The development environment is based on Visual Studio 2013. NET Framework 4.5, when running, you should pay attention to meet the requirements, OK, the following straight to the point.
Let's take a look at the implementation principle first. Basic principle: A page for file upload, another page to listen to the file upload how much.
Here are two places to explain: the first one, how to know that the monitoring of the file is uploaded this file? The implementation mechanism is very simple, that is, let asp.net produce a unique GUID, this ID number is unique, through Ajax to assign value to a hidden field; second, how do I get the file information for the GUID flag? Through the ASP.net caching mechanism, upload the process, will upload information to the cache to write, until the file upload completed, and in another through the GUID to get the cached information, information including the information you want, such as how many bytes uploaded, how long to spend. Well, the main point is explained here, if you have any questions, give me a message.
Here's a concrete implementation:
The file directory structure is as follows:

Index.htm is the File upload page, submit form to the Uploadhandler directory default.aspx to achieve file upload. The three files in the
Progresshandler directory are abort.ashx, genericguid.ashx,handler.ashx functions are: Cancel the file being uploaded based on the GUID, generate the GUID, and obtain the upload information based on the GUID.
The first step: 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.

<! 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&G 
 T <meta name= "Author" content= "Li Jiu Quan"/> <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> </ head> <body> <div id= "Upload_demo" > <div class= "title" >asp.net Ajax File Upload progress bar example </div> &L T;form action= "uploadhandler/default.aspx" enctype= "multIpart/form-data "method=" post "target=" Upload_hidden_iframe "> <input id=" GUID "Name=" GUID "value=" type= "Hidde N "/> <p>* is suitable for small file uploads, not exceeding 80mb</p> <p> file address </p> <input name=" Upload_file "type=" E "/> <br/> <p> file description </p> <textarea name=" Description_file "></textarea> &L t;br/> <br/> <input type= "Submit" value= "Upload file"/> </form> </div> <div id= "b Ack_panel "></div> <div id=" Upload_panel "> <div id=" upload_title "> File upload </div> <div id= "Upload_content" > <ul> <li id= "Finished_percent" > is ready to upload ...</li> <li><div id= "Upload_bar" ><div id= "upload_progress" ></div></div></li> <li id= "Upload_speed" > </li> <li id= "Upload_costtime" ></li> <li id= "upload_filesize" ></li> <li ID = "Upload_filename" ></li&Gt </ul> <div id= "Upload_detail" ></div> <div id= "Upload_choose" > <span id= "Upload_c 
 Ancel "> Cancel </span><span id=" Upload_submit "> OK </span> </div> </div> </div> <iframe name= "Upload_hidden_iframe" style= "Display:none;"  ></iframe> </body> </html>

The second step, creating a Generateguid.ashx file, is 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>///gets the GUID of the uploaded file/// t;/summary>///<param name= "context" > Current request entity </param>///<CREATTIME>2015-06-28</CREATTIME&G 
  T <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 {false;} } 
 
 } 
} 

The third step is to create a default.aspx file that uploads 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 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 &gt; 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 &gt; 0&amp;&amp;!abort) {_fstream.write (Buffer,0,len); 
   DateTime end = DateTime.Now.ToLocalTime (); Info. Costtime = (long) (End-begin). 
   TotalMilliseconds; Info. 
 
   filefinished = Len; 
 
   Analog delay used, the actual application when the cancellation of his 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 + Uploadfilena 
   ME); } 
  } 
 } 
  
}

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

&lt;%@ WebHandler language= "C #" class= "Progresshandler.handler"%&gt; using System.Web; 
 
Using System.Xml.Linq; Namespace Progresshandler {public class Handler:ihttphandler {///&lt;summary&gt;///get upload file Progress///&lt;  
  /summary&gt;///&lt;param name= "context" &gt; Current request entity &lt;/param&gt;///&lt;creattime&gt;2015-06-28&lt;/creattime&gt; &lt;author&gt;FreshMan&lt;/author&gt; 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 {false;}  } 
 } 
}

Step Fifth to create a abort.ashx file to cancel the upload.

 &lt;%@ WebHandler language= "C #" class= "Progresshandler.abort"%&gt; using System.Web; 
 
Using System.Xml.Linq; Namespace Progresshandler {public class Abort:ihttphandler {///&lt;summary&gt;///cancel upload handler///&lt;/su 
  mmary&gt;///&lt;param name= "context" &gt; Current request entity &lt;/param&gt;///&lt;creattime&gt;2015-06-28&lt;/creattime&gt; &lt;author&gt;FreshMan&lt;/author&gt; public void ProcessRequest (HttpContext context) {context. 
   Response.ContentType = "Application/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 {false;}  } 
 
 } 
}

OK, here's the JavaScript script, I've referenced the jquery framework, and I've used the UI framework. The
Core code is the Ajax-progress-upload.js file, plus 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" 
 }); 
 The function () {$ (this). css ({"Color": "#1c94cd", "Border": "1px solid #ddd"}); 
 }); $ ("#upload_cancel"). Click (function () {$.ajax ({URL: _abort_url, data: {GUID: _guid, abort:true}, Datat 
    ype: "xml", type: "Post", Success:function () {$ ("#upload_panel"). Fadeout (' fast '); 
    $ ("#back_panel"). fadeout (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 ("No upload file specified!"). 
   "); 
  return false; 
  $ ("#upload_progress"). CSS ("width", "0%"); 
  $ ("#finished_percent"). HTML ("Ready to 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 (' 1000 '); }, Success:function (response) {if (response). Find ("root abort"). Text () = = "true" {$ ("#upload_panel 
     "). Fadeout (' fast '); 
     $ ("#back_panel"). fadeout (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) &lt; 1024) {_speed = Ljq.tofix (_speed) + "Kb"; 
     else {_speed = Ljq.tofix (_speed/1024) + Mb; 
     } if (parseint (_filesize)/1024 &lt; 1024) {_filesize = Ljq.tofix (_filesize/1024) + "Kb"; 
     else if (parseint (_filesize)/1024/1024 &lt; 1024) {_filesize = Ljq.tofix (_filesize/1024/1024) + Mb; 
     else {_filesize = Ljq.tofix (_filesize/1024/1024/1024) + Gb; 
     } if (_upload_costtime &lt; 1000) {_upload_costtime = _upload_costtime + "MS"; else if (_upload_costtime/1000 &lt;) {_upload_costtime = parseint (_upload_costtime/1000) + "seconds" + _upload_ 
     Costtime% 1000 + "MS"; else {_upload_costtime = PARseint (_UPLOAD_COSTTIME/1000/60) + "min" + parseint ((_upload_costtime% 60000)/1000) + "SEC" + _upload_costtime% 1000 + 
     "Milliseconds"; 
     $ ("#upload_progress"). CSS ("width", parseint (_percent) + "%"); 
     $ ("#finished_percent"). HTML ("percent complete:" + 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 consuming:" + _upload_costtime); 
      if (_percent &gt;=) {window.clearinterval (_timer); $ ("#finished_percent"). HTML ("&lt;span style= ' color:green; ') 
     &gt; File Upload complete &lt;/span&gt; "); 
     } if (_cancel) {window.clearinterval (_timer); 
 
  }}, Error:function () {}}; 
 
 _timer = Window.setinterval (function () {$.ajax (_option);}, 1000); 
 
});  });

The above is the main part of the code. asp.net single file with progress bar upload, not belong to task control, also not flash type upload, completely is asp.net, JS, CSS implementation upload. Source code for the development of beta, need to use the pro need to pay attention to modify the configuration file.

Download the project source please click here: Http://xiazai.jb51.net/201509/yuanma/asp_net_progressbar (jb51.net). 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.