js HTML5 Ajax implements the file upload progress bar function
- 2020-12-20 03:27:41
- OfStack
This paper introduces js combined with HTML5 Ajax to realize the function of file upload progress bar, and shares it for your reference. The specific content is as follows
1. lib.js
var Host = window.location.host;
//--Cookie
function setCookie(name,value)
{
var Days = 30;
var exp = new Date();
exp.setTime(exp.getTime() + Days*24*60*60*1000);
document.cookie = name + '='+ escape (value) + ';expires=' + exp.toGMTString();
}
function getCookie(name)
{
var arr,reg=new RegExp('(^| )'+name+'=([^;]*)(;|$)');
if(arr=document.cookie.match(reg))
return unescape(arr[2]);
else
return null;
}
//--Dom & String
var get = {
//-- To obtain Dom Id
Id:function(obj)
{
return is.object(obj) ? obj : (document.getElementById(obj));
},
//-- To obtain Body
body:function()
{
return document.body;
},
//-- through Html Tag fetch object
Tag:function(obj, Tagname)
{
return obj.getElementsByTagName(Tagname);
},
//-- through Name To pick up objects
Name:function (Name)
{
return document.getElementsByName(Name);
},
//-- Url Code conversion
encode:function (str)
{
return encodeURIComponent(str);
},
filepath:function (obj,callback)
{
window.URL = window.URL || window.webkitURL;
img = new Image();
var reader = new FileReader();
reader.readAsDataURL(get.Id(obj).files[0]);
reader.onload = function(e){
callback(this.result);
source = this.result;
}
// return window.URL.createObjectURL(get.Id(obj).files[0]);
}
}
var set = {
//-- url jump
url:function(URL)
{
window.location.href = URL;
},
//-- A page refresh
reload:function()
{
window.location.reload();
},
//-- Dynamic setting Label content @ obj Is the tag content, text For content
html:function (obj, text)
{
obj.innerHTML = text;
}
}
var string = {
//-- Converts a character to Json
toJson:function(str)
{
return eval('('+str+')');
},
//-- Case insensitive judgment equal true ,
eqlower:function(str1, str2)
{
if(str1.toLowerCase() == str2.toLowerCase()){
return true;
}
return false;
}
}
var is = {
//-- Whether it is IE The browser , Use this to determine if it is supported HTML5 , below IE10 The return of false Because of IE using V8 JavaScript engine
html5:function ()
{
return (!/*@cc_on!@*/~0x1111111111111111) ? false : true;
},
//-- Verify id card, and return ID card, gender, address, age
Card:function (sId) {
var card_area={
11:' Beijing ', 12:' tianjin ', 13:' hebei ', 14:' shanxi ', 21:' liaoning ', 15:' Inner Mongolia ',
22:' Ji Lin ', 31:' Shanghai ', 32:' jiangsu ', 33:' zhejiang ', 34:' anhui ', 23:' heilongjiang ',
35:' fujian ', 36:' jiangxi ', 37:' shandong ', 41:' henan ', 42:' hubei ', 43:' hunan ',
44:' guangdong ', 45:' guangxi ', 46:' hainan ', 50:' chongqing ', 51:'4 sichuan ', 52:' guizhou ',
53:' yunnan ', 54:' Tibet ', 61:' shaanxi ', 62:' gansu ', 63:' qinghai ', 64:' ningxia ',
65:' xinjiang ', 71:' Taiwan ', 81:' Hong Kong ', 82:' Macau ', 91:' foreign '
};
var iSum=0
var info=''
var card_info=Array(2);
var error = '';
sId=sId.replace(/x$/i,'a');
if (sId.length==0){
error = ' Please fill in your ID card ';
return false;
}
if (null == card_area[parseInt(sId.substr(0,2))]) {
error = ' Illegal id Your area has been filled out incorrectly please fill it out carefully ';
return false;
}
sBirthday=sId.substr(6,4)+'-'+Number(sId.substr(10,2)) + '-'+Number(sId.substr(12,2));
var d = new Date(sBirthday.replace(/-/g,'/'));
if (sBirthday!=(d.getFullYear()+'-'+ (d.getMonth()+1) + '-' + d.getDate())) {
error = ' Your date of birth is incorrect. Please fill it out carefully ';
return false;
}
for(var i = 17; i>=0; i--)
{
iSum += (Math.pow(2,i) % 11) *
parseInt(sId.charAt(17 - i),11)
}
if (1 != iSum%11) {
error = ' If you confirm that you are an earthman, please fill it out carefully ~~~~';
return false;
}
if (sId.length>19){
error = ' Are you sure your ID card is valid? ';
return false;
}
card_info[0] = card_area[parseInt(sId.substr(0, 2))];
card_info[1] = sBirthday;
card_info[2] = sId.substr(16, 1) % 2 ? ' male ' : ' female ';
return card_info;
},
//-- Gets the type of the variable, object . string . int..... Etc.
type:function(type)
{
if(is.object(type)) {
return 'object';
}else if (is.string(type)) {
return 'string';
}else if (is.int(type)) {
return 'int';
}else if (is.double(type)) {
return 'double';
}else {
return 'null';
}
},
//-- Is the variable an object? Returns true|false
object:function(type)
{
return 'object' == typeof(type) ? true:false;
},
//-- Is the variable a string . return true|false
string:function(type)
{
return 'string' == typeof(type) ? true:false;
},
//-- Whether the variable is an integer, returns true|false
int:function(type)
{
if ('number' == typeof(type)) {
if(0 > type.toString().indexOf('.')) {
return true;
}
}
return false;
},
//-- Returns if the variable is a decimal true|false
double:function(type)
{
if('number' == typeof(type)) {
if (0<=type.toString().indexOf('.')) {
return true;
}
}
return false;
}
}
var file = {
//-- Asynchronous file upload
upload:function (json)
{
var post = new XMLHttpRequest();
var FLIE = new Object();
var json = is.object(json) ? json : string.toJson(json);
var dataType = string.eqlower(json.dataType,'json') ? true : false;
var fileSize = 0;
if(!json.url&&json.error) {
json.error(404);
return;
}
if(!is.object(json.file)) {
FLIE.id = get.Id(json.file);
//-- Large file processing
if(json.maxfile) {
//-- Total file size
fileSize = file.getSize(FLIE.id);
//-- In order to 2M Perform file cutting for units
shardSize = 1024 * 1024 << 1;
//-- The total number of pieces
shardCount = Math.ceil(fileSize / shardSize);
for(var i = 0; i < shardCount; ++i)
{
//-- Calculate each 1 The starting and ending positions of the slice
var start = i * shardSize;
var end = Math.min(fileSize, start + shardSize);
var formData = new FormData();
//--slice Method used to cut out files 1 Part of the
formData.append(json.file, FLIE.id.files[0].slice(start,end));
formData.append("total", shardCount); // The total number of pieces
formData.append("index", i + 1); // Which is the current film
post.upload.addEventListener('progress', callback, false);
post.open('post', json.url, true); // Asynchronous transmission
post.send(formData);
post.upload.onprogress = function (ev) {
if(file.getProgress(ev) == 100) {
json.success(ev);
}
}
}
}else {
var formData = new FormData();
formData.append(json.file, FLIE.id.files[0]);
if (json.progress) {
post.upload.addEventListener('progress', json.progress, false);
}
post.open('post', json.url, true); // Asynchronous transmission
post.send(formData);
/*post.upload.onprogress = function (ev) {
if(file.getProgress(ev) == 100) {
json.success(ev);
}
}*/
post.onreadystatechange = function () {
switch (post.readyState) {
case 1:{break;}
case 2:{break;}
case 3:{break;}
case 4:{
if (post.status == 200 || post.status == 0) {
json.success(string.toJson(post.responseText));
}
break;
}
}
}
}
}
},
//-- Gets the progress value of the uploaded file
getProgress:function (evt) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
return percentComplete.toString();
},
//-- Gets the size of the file
getSize:function (file) {
var FILE = get.Id(file).files[0];
var fileSize = 0;
if (file.size > 1024 * 1024) {
fileSize = (Math.round(FILE.size * 100 / (1024 * 1024)) / 100).toString();
} else {
fileSize = (Math.round(FILE.size * 100 / 1024) / 100).toString();
}
return fileSize;
},
//-- Gets the type of file
getType:function (file) {
var FILE = get.Id(file).files[0];
return FILE.type;
},
//-- Get the name of the file
getName:function (file) {
var FILE = get.Id(file).files[0];
return FILE.name;
},
//-- Include file
include:function (path) {
}
}
//--Ajax Data submission class
var Call = {
/**
* Parameters for json object |Json String,
* @type post|get The default is get , request mode
* @url String String type , Request the address
* @loading bool true|false Whether animation is enabled or not
* @time int Animation time if loading for false Do not set this parameter
* @data Json | String Submitted data
* @sucess The callback function This has to have
*/
Ajax:function(json){
var json = is.object(json)?json:string.toJson(json);
var type = (json.type == undefined) || (json.type == '') ? 'get' : json.type; ;
var url = (json.url == undefined) || (json.url == '') ? alert(' request url Can't be empty ') : json.url;
var loading = (json.Loading == undefined) || (json.Loading == '') ? false : json.Loading;
var time = (json.time == undefined) || (json.time == '') ? 2000 : json.time;
var dataType = string.eqlower(json.dataType,'json') ? 'json' : 'string';
if(loading) { var L = Loading.start(); }
var data = '';
if(is.object(json.data)) {
if(json.data) {
for(d in json.data) {
data = data + d + '=' + json.data[d] + '&';
}
}
if(string.eqlower(json.type,'get')) {
data ='?' + data.substring(0, data.length-1);
}
}else{
if(json.data.length>=1) {
data = json.data.indexOf('?') < 0 ? '?'+json.data:json.data+'';
}
}
try {
//--IE High version creation XMLHTTP
XMLHttpReq = new ActiveXObject('Msxml2.XMLHTTP');
}
catch(E) {
try {
XMLHttpReq = new ActiveXObject('Microsoft.XMLHTTP');//IE Lower version creation XMLHTTP
}
catch(E) {
XMLHttpReq = new XMLHttpRequest();// Compatible with the IE Browser, create directly XMLHTTP object
}
}
if(XMLHttpReq) {
if (string.eqlower(json.type, 'post')) {
XMLHttpReq.open('post', url, true);
XMLHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
XMLHttpReq.send(data);
}else if (string.eqlower(json.type, 'get')) {
XMLHttpReq.open('get', url+data, true);
XMLHttpReq.send(null);
}
XMLHttpReq.onreadystatechange = function () {
switch (XMLHttpReq.readyState) {
case 1:{break;}
case 2:{break;}
case 3:{break;}
case 4:{
if (XMLHttpReq.status == 200 || XMLHttpReq.status == 0) {
if (loading) {
setTimeout(function(){
Loading.stop(L);
if(json.dataType == 'json')
json.success(string.toJson(XMLHttpReq.responseText));
else
json.success(XMLHttpReq.responseText)
}, time*1000);
}else {
if(json.dataType == 'json')
json.success(string.toJson(XMLHttpReq.responseText));
else
json.success(XMLHttpReq.responseText)
}
}
break;
}
}
}
}
}
}
var Loading = {
//-- Ajax animation
start:function(){
var d = add.Dom(document.body,'style');
d.innerHTML = '@keyframes d{from {left:0px;}to {left:98%;}}';
var back = add.Dom(document.body, 'div');
var d0 = add.Dom(back, 'div');
var d1 = add.Dom(d0, 'div');
var d2 = add.Dom(d0, 'div');
var d3 = add.Dom(d0, 'div');
var d4 = add.Dom(d0, 'div');
add.Attr(back, 'style', 'width:100%;height:100%;filter:alpha(opacity=50); -moz-opacity:0.5; opacity:0.5; background:#000; position:fixed; left:0px; top:0px; z-index;1000;');
add.Attr(d0, 'style', 'position:relative; top:50%; width:100%; height:30px;');
add.Attr(d1, 'style', 'height:15px; width:15px; position:absolute; background:#ABCDEF; animation:d 2s infinite; -moz-border-radius:15px; -webkit-border-radius: 15px; border-radius: 15px 15px 15px 15px; ');
add.Attr(d2, 'style', 'height:15px; width:15px; position:absolute; background:#ABCDEF; animation:d 3s infinite; -moz-border-radius:15px; -webkit-border-radius: 15px; border-radius: 15px 15px 15px 15px; ');
add.Attr(d3, 'style', 'height:15px; width:15px; position:absolute; background:#ABCDEF; animation:d 4s infinite; -moz-border-radius:15px; -webkit-border-radius: 15px; border-radius: 15px 15px 15px 15px; ');
add.Attr(d4, 'style', 'height:15px; width:15px; position:absolute; background:#ABCDEF; animation:d 5s infinite; -moz-border-radius:15px; -webkit-border-radius: 15px; border-radius: 15px 15px 15px 15px; ');
var div = { domback:back, dom0:d0, dom1:d1, dom2:d2, dom3:d3, dom4:d4 }
return div;
},
//-- Ajax To stop the animation
stop:function(d) {
d.dom0.parentNode.removeChild(d.dom0);
d.dom1.parentNode.removeChild(d.dom1);
d.dom2.parentNode.removeChild(d.dom2);
d.dom3.parentNode.removeChild(d.dom3);
d.dom4.parentNode.removeChild(d.dom4);
d.domback.parentNode.removeChild(d.domback);
}
}
var del = {
Dom:function(obj) {
obj.parentNode.removeChild(obj);
}
}
var add = {
//-- Dynamically add Dom node
Dom:function (obj,dom) {
var dom = document.createElement(dom);
get.Id(obj).appendChild(dom);
return dom;
},
//-- Add properties dynamically
Attr:function(obj,key,value){
obj.setAttribute(key, value);
return obj;
}
}
//--URL coding
function url(Str){
return decodeURI(Str);
}
/**
* Template string, syntax tag used <js></js>
* Fully follow javascript Native grammar
* @param template
* @param vars
* @returns {Function}
*/
function js_template(template, vars) {
// only 1 Delimiter string
var split = '_{' + Math.random() + '}_';
// Eliminate newline characters
var estr = template.replace(/\n|\r|\t/g, '');
var js = [];
/****
* Match the label <js> ...</js>-- And replace it with a particular delimiter string,
* And will match js Code into js Spare in array
* */
estr = estr.replace(/<js>(.*?)<\/js>/g, function ($0, $1) {
js.push($1);
return split;
});
/* To separate by a particular delimiter string text An array of text strings */
var text = estr.split(split);
estr = " var output='';";
/****
* 0101010---0 for text[] The element ,1 for js[] The element
* Recatenation joins for execution eval the estr
* **/
for (var i = 0; i < js.length; ++i) {
estr += 'output+=text[' + i + '];';
estr += js[i];
}
estr += 'output+=text[' + js.length + '];';
estr += 'return output;';
var fun =new Function('vars','text',estr);
return function(data){
return fun.apply(null,[data,text]);
}
}
2. add.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"><title>Lumino Pro - Dashboard</title>
<link href="__SOURCE__/css/bootstrap.min.css" rel="stylesheet">
<link href="__SOURCE__/css/datepicker3.css" rel="stylesheet">
<link href="__SOURCE__/css/styles.css" rel="stylesheet">
<link href="__SOURCE__/css/Table.css" rel="stylesheet">
<link href="__SOURCE__/css/dt.css" rel="stylesheet">
<link href="__SOURCE__/css/plus/buttons.css" rel="stylesheet">
<link href="__SOURCE__/css/file.css" rel="stylesheet">
<link href="__SOURCE__/css/webuploader.css" rel="stylesheet">
<link href="__SOURCE__/css/plus/bootstrap-switch.min.css" rel="stylesheet">
<link href='http://fonts.useso.com/css?family=Lato:100,300,400,700,900,100italic,300italic,400italic,700italic,900italic' rel='stylesheet' type='text/css'>
<!--[if lt IE 9]>
<link href="__SOURCE__/css/rgba-fallback.css" rel="stylesheet">
<script src="__SOURCE__/js/html5shiv.js"></script>
<script src="__SOURCE__/js/respond.min.js"></script>
<![endif]-->
</head>
<body>
<include file="Apps/Admin/View/include/nav.html"/>
<div id="sidebar-collapse" class="col-sm-3 col-lg-2 sidebar">
<form role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
</form>
<include file="Apps/Admin/View/include/menu.html"/>
</div><!--/.sidebar-->
<div class="col-sm-9 col-sm-offset-3 col-lg-10 col-lg-offset-2 main">
<div class="row">
<ol class="breadcrumb">
<li><a href="#"><span class="glyphicon glyphicon-home"></span></a></li>
<li class="active">Dashboard</li>
</ol>
</div>
<div class="row col-no-gutter-container">
<div class="panel panel-default">
<div class="panel-heading">Banner add
<button id='up' type="button" style='float:right; margin:4px;"' class="btn btn-default"><span class="glyphicon glyphicon-plus"></span> upload </button>
<button id='add' type="button" style='float:right; margin:4px;"' class="btn btn-default"><span class="glyphicon glyphicon-plus"></span> Sure to add </button>
</div>
<div class="panel-body">
<div class="canvas-wrapper">
<form id='banner'>
<dl class='dt'>
<dd><label>Banner The name </label></dd>
<dt>
<div class="form-group has-success">
<input name='name' class="form-control" placeholder="Banner The name " value=''>
</div>
</dt>
<div style='clear:both;'></div>
<dd><label>Banner type :</label></dd>
<dt>
<div class="form-group has-warning">
<select name='type' class="form-control" style='background:rgb(31,45,55); color:#FFF;'>
<option value='1' style=' font-size:18px;'> Home page </option>
<option value='2' style=' font-size:18px;'> Inside pages of advertising </option>
</select>
</div>
</dt>
<div style='clear:both;'></div>
<dd><label>Banner The link address :</label></dd>
<dt>
<div class="form-group has-warning">
<input name='link' class="form-control" placeholder="Banner The link address " value=''>
</div>
</dt>
</dl>
<dl class='dt'>
<dd><label>Banner upload :</label></dd>
<dt>
<div class="form-group has-warning">
<input class="form-control" type = 'button' value=' Select the file '>
<input id='files' type='file' class="file">
</div>
</dt>
<div style='clear:both;'></div>
<dd><label> The file type :</label></dd>
<dt>
<div class="form-group has-warning">
<div id='filetype' class='left' style='padding-top:2px;'></div>
</div>
</dt>
<div style='clear:both;'></div>
<dd><label> File upload progress :</label></dd>
<dt>
<div class='form-control' style='padding:2px; height:26px; overflow:hidden;'>
<!-- <div id='progress' style='background:#ABCDEF; width:0px; height:22px;'></div> -->
<progress id='progress' max="100" value='0' style='width:100%; height:22px; background:#30a5ff;'>o( � � � )o</progress>
<div id='gress' height:0px; style='padding-top:2px; color:#FFF; position:relative; bottom:28px; left:40%;'></div>
</div>
<div id='fileSize' class='right' style='padding-top:2px;'>
<span class='left'></span>
<span></span>
</div>
</dt>
</dl>
</form>
<div style='clear:both;'></div>
<div class='fixed-table-container' style='height:244px;'>
<img class='left' id ='thmb' src=''>
<div>
<ul class='ul-info' style='display:none;'>
<li><span class='left'> The file size :</span><p>22222kb</p></li>
<li><span class='left'> The file path :</span><p>22222kb</p></li>
<li><span class='left'> Picture height :</span><p>22222kb</p></li>
<li><span class='left'> Image width :</span><p>22222kb</p></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div> <!--/.main-->
</div>
<script src="__SOURCE__/js/jquery-1.11.1.min.js"></script>
<script src="__SOURCE__/js/bootstrap.min.js"></script>
<script src="__SOURCE__/js/file.js"></script>
<script type="text/javascript" src="__SOURCE__/js/plus/bootstrap-datetimepicker.de.js" charset="UTF-8"></script>
<script src="__SOURCE__/js/plus/bootstrap-switch.min.js"></script>
<script src="__SOURCE__/js/table.js"></script>
<script type="text/javascript" src='__SOURCE__/js/lib.js'></script>
<script>
var data = new Object();
get.Id('files').onchange = function () {
get.filepath(this,function(str){
get.Id('thmb').src = str;
});
set.html(filetype,file.getName('files'));
get.Id('progress').value = 0;
set.html(get.Id('gress'),'');
set.html(get.Tag(get.Id('fileSize'), 'span')[0], file.getSize('files') + 'KB');
set.html(get.Tag(get.Id('fileSize'), 'span')[1], '/0kb');
}
get.Id('up').onclick = function () {
if(file.getSize('files')<=0) {
return false;
}
file.upload({
form:'banner', //form the id
url:'{:U('Banner/add',0,0)}', // The address of the upload request file
//maxfile:true, // Whether to enable large file uploads
dataType:'json',
progress:function(ev) { //-- Progress callback function in upload
get.Id('progress').value = file.getProgress(ev);
// Get the upload progress file.getProgress(ev)
set.html(get.Id('gress'),file.getProgress(ev)+'%');
set.html(get.Tag(get.Id('fileSize'), 'span')[1], '/' + file.getProgress(ev) * (file.getSize('files') / 100 >>0) + 'KB');
},
file:'files', //-- File input box id
//-- After uploading, the background returns the callback function
success:function(e){
set.html(get.Tag(get.Id('fileSize'), 'span')[1], '/' + file.getSize('files') + 'KB');
set.html(get.Id('gress'),' Upload to complete ');
data.bannerWidth = e.bannerWidth;
data.bannerHeight = e.bannerHeight;
data.bannerTyle = e.bannerTyle;
data.bannerImg = e.bannerImg;
}
});
}
get.Id('add').onclick = function () {
data.name = get.Name('name')[0].value;
data.type = get.Name('type')[0].value;
data.link = get.Name('link')[0].value;
data.act = 'add';
Call.Ajax({
type:'post', // Request way
Loading:true, // Whether to start animation or not
time:5, // The animation is displayed for a few seconds
url:'{:U('Banner/add',0,0)}?act=add', // Request the address
data:data, // Sent data
dataType:'json', //Ajax The data type returned , can be String
success:function (e) { // The callback function
set.url(e.url);
}
});
}
</script>
</body>
</html>
I hope this article has been helpful in learning javascript programming.