BootStrap Progressbar Implementation of large file upload progress bar example code

  • 2021-07-01 06:08:44
  • OfStack

1. First of all, realize the upload of large files. If it is a few megabytes or a few 10 megabytes of files, it is OK to upload them in a basic way, but if it is a large file upload, it is best to upload them in pieces. I here is mainly used in the client fragment read to the server segment, and then save, to read the server segment after the fragment data will be combined.

2. The front-end code is as follows:


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UploadTest2.aspx.cs" Inherits="Html5UploadTest.UploadTest2" %>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>HTML5 Example of large file slice upload </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");
var file = $("#file")[0].files[0], // File object 
fileNum = $("#file")[0].files[0].length,
name = file.name, // Filename 
size = file.size, // Total size 
succeed = 0;
var shardSize = 2 * 1024 * 1024, // With 2MB For 1 Pieces 
shardCount = Math.ceil(size / shardSize); // Total number of slices 
$('.progress .progress-bar').attr('data-transitiongoal', 0).progressbar({ display_text: 'fill' });
for (var i = 0; i < shardCount; ++i) {
// Calculate every 1 Start and end positions of slices 
var start = i * shardSize,
end = Math.min(size, start + shardSize);
// Structure 1 A form, FormData Yes HTML5 Added 
var form = new FormData();
form.append("data", file.slice(start, end)); //slice Method is used to cut out the 1 Part 
form.append("name", name);
form.append("total", shardCount); // Total number of slices 
form.append("index", i + 1); // What is the current slice 
//Ajax Submit 
$.ajax({
url: "Upload.ashx",
type: "POST",
data: form,
async: true, // Asynchronous 
processData: false, // It's important, tell me jquery Don't be right form Process 
contentType: false, // Important, specified as false To form the correct Content-Type
success: function () {
++succeed;
$("#output").text(succeed + " / " + shardCount);
var percent = ((succeed / shardCount).toFixed(2)) * 100;
updateProgress(percent);
if (succeed == shardCount) {
$("#upload").removeAttr("disabled");
}
}
});
}
}
function progress(percent, $element) {
var progressBarWidth = percent * $element.width() / 100;
$element.find('div').animate({ width: progressBarWidth }, 500).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>
</head>
<body>
<input type="file" id="file" />
<button id="upload" onclick="uploadFile();"> Upload </button>
<span id="output" style="font-size: 12px"> Wait </span>
<div class="progress">
<div id="progressBar" class="progress-bar" role="progressbar" data-transitiongoal=""></div>
</div>
</body>
</html>

3. The background 1 handler is as follows:


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
namespace Html5UploadTest
{
/// <summary>
/// Summary description for Upload
/// </summary>
public class Upload : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
try
{
// From Request Take parameters in, pay attention to the uploaded file in Requst.Files Medium 
string name = context.Request["name"];
int total = Convert.ToInt32(context.Request["total"]);
int index = Convert.ToInt32(context.Request["index"]);
var data = context.Request.Files["data"];
// Save 1 Pieces to disk 
string dir = context.Request.MapPath("~/temp");
string file = Path.Combine(dir, name + "_" + index);
data.SaveAs(file);
// If it's already the last 1 Pieces, combinations 
// Of course, you can also use other methods, such as receiving each fragment and writing it directly to the corresponding location of the final file, but you should control concurrency and prevent file lock conflicts 
if (index == total)
{
file = Path.Combine(dir, name);
//byte[] bytes = null;
using (FileStream fs = new FileStream(file, FileMode.OpenOrCreate))
{
for (int i = 1; i <= total; ++i)
{
string part = 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;
}
// Returns whether it is successful, which is simplified here 
//return Json(new { Error = 0 });
}
public bool IsReusable
{
get
{
return false;
}
}
}
}

4. Of course, the background still needs 1 exception handling or power failure continuation work to be done, to be continued. . .


Related articles: