BootStrap Progressbar Implementation of large file upload progress bar

Source: Internet
Author: User
Tags file upload progress bar

1. The first implementation of large file upload, if it is a few megabytes or a few 10 trillion files with the basic upload method can be, but if it is a large file upload, it is best to use the way of multipart upload. I am here mainly using the client to read the Shard to the server segment, and then save, to the server segment after reading the Shard data to be combined.

2. The front-end code is as follows:

<%@ Page language="C #"autoeventwireup="true"Codebehind="UploadTest2.aspx.cs"inherits="Html5uploadtest.uploadtest2"%>"ZH-CN">"Utf-8"> &LT;TITLE&GT;HTML5 Large file multipart upload example </title> <script src="Scripts/jquery-1.8.2.js"></script> <link href="Bootstrap-progressbar/bootstrap-progressbar-3.3.4.css"Rel="stylesheet"/> <script src="Bootstrap-progressbar/bootstrap-progressbar.js"></script> <%--<link href="Jqueryui/jquery-ui.css"Rel="stylesheet"/> <script src="Jqueryui/jquery-ui.js"></script>--%> <script>function UploadFile () {$ ("#upload"). attr ("Disabled","Disabled"); varFile = $ ("#file")[0].files[0],//File ObjectFileNum = $ ("#file")[0].files[0].length, name= File.name,//file nameSize = File.size,//Total sizesucceed =0; varShardsize =2*1024x768*1024x768,//with 2MB as a shardShardcount = Math.ceil (size/shardsize);//total number of pieces$('. Progress. Progress-bar'). attr ('Data-transitiongoal',0). ProgressBar ({display_text:'Fill' });  for(vari =0; i < Shardcount; ++i) {//calculate the start and end positions of each slice                varstart = i *shardsize, End= math.min (size, start +shardsize); //constructs a form, Formdata is the HTML5 new                varform =NewFormData (); Form.append ("Data", File.slice (start, end));//slice method used to cut out part of a fileForm.append ("name", name); Form.append (" Total", Shardcount);//total number of piecesForm.append ("Index", i +1);//The current is the first few pieces//Ajax Submissions$.ajax ({URL:"upload.ashx", type:"POST", Data:form,Async:true,//AsynchronousProcessData:false,//It's important to tell jquery not to handle the form.ContentType:false,//It is important to specify false to form the correct content-typesuccess:function () {++succeed; $("#output"). Text (Succeed +" / "+shardcount); varPercent = ((Succeed/shardcount). ToFixed (2)) * -;                        UpdateProgress (percent); if(Succeed = =Shardcount) {                            $("#upload"). Removeattr ("Disabled");            }                    }                }); }} function progress (percent, $element) {varProgressbarwidth = percent * $element. Width ()/ -; $element. Find ('Div'). Animate ({width:progressbarwidth}, -). HTML (Percent +"% "); }                //$ (document). Ready (function () {//$ ('. Progress. Progress-bar '). ProgressBar ({display_text: ' Fill '}); //});function UpdateProgress (percentage) {$ ('. Progress. Progress-bar'). attr ('Data-transitiongoal', percentage). ProgressBar ({display_text:'Fill' }); }    </script>"file"Id="file"/> <button id="Upload"onclick="UploadFile ();"> Uploads </button> <span id="Output"style="font-size:12px"> Wait </span> <divclass="Progress"> <div id="ProgressBar" class="Progress-bar"role="ProgressBar"Data-transitiongoal=""></div> </div></body>View Code

3. Background general processing procedures are as follows:

usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingsystem.web;namespacehtml5uploadtest{/// <summary>    ///Summary description for Upload/// </summary>     Public classUpload:ihttphandler { Public voidProcessRequest (HttpContext context) {context. Response.ContentType="Text/plain"; Try            {                //take the parameters from request and note that the uploaded files are in Requst.files                stringName = Context. request["name"]; intTotal = Convert.ToInt32 (context. request[" Total"]); intIndex = Convert.ToInt32 (context. request["Index"]); varData = context. request.files["Data"]; //Save a shard to disk                stringDir = context. Request.mappath ("~/temp"); stringFile = Path.Combine (dir, name +"_"+index); Data.                SaveAs (file); //if it is already the last Shard, the combination//of course, you can also use other methods such as receiving each shard directly to the corresponding location of the final file, but to control the concurrency to prevent file lock conflicts                if(Index = =Total ) {File=Path.Combine (dir, name); //byte[] bytes = null;                    using(FileStream fs =NewFileStream (file, FileMode.OpenOrCreate)) {                         for(inti =1; I <= total; ++i) {stringPart = Path.Combine (dir, name +"_"+i); //bytes = System.IO.File.ReadAllBytes (part); //FS. Write (bytes, 0, bytes.                            Length); //bytes = null;System.IO.File.Delete (part); Fs.                        Close (); }                    }                }            }            Catch(Exception) {Throw; }            //return is successful, simplified processing is done here//return Json (new {Error = 0});        }         Public BOOLisreusable {Get            {                return false; }        }    }}
View Code

4. Of course, the backstage also need some abnormal handling or power off the work to be done, to be continued ...

BootStrap Progressbar Implementation of large file upload progress bar

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.