jQuery多文件异步上传带进度条实例代码


Posted in Javascript onAugust 16, 2016

先给大家展示下效果图:

jQuery多文件异步上传带进度条实例代码

///作者:柯锦
///完成时间:2016.08.16
///多文件异步上传带进度条
(function ($) {
function bytesToSize(bytes) {
if (bytes === 0) return '0 B';
var k = 1024, // or 1000
sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
i = Math.floor(Math.log(bytes) / Math.log(k));
return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
}
function changeCursor(obj) {
obj.style.cursor = 'pointer'
}
function deleteSelfAndFile(obj) {
var that = $(obj);
var parentLi = that.parent("li");
that.remove();
parentLi.remove();
}
function CreateXMLHttpRequest(target) {
var xhr = new XMLHttpRequest();
//var ops = $.data(target, "KJajaxUpload").Options;
//var v, h, evs = { loadstart: 0, loadend: 0, progress: 0, load: 0, error: 0, abort: 0 };
//for (v in evs) {
// if (h = ops['on' + v]) {
// xhr.upload.addEventListener(v, h, false);
// }
//}
return xhr;
}
function InitFileDiv(target, options) {
var _that = $(target);
var width = _that.width();
var hasUploadedDiv = $("<div class='KJajaxUpload_HasUploaded'/>");
hasUploadedDiv.css({
width: "100%"
});
_that.append(hasUploadedDiv);// 上
var divClear = $("<div style='clear:both;'></div>");
var divUploadBody = $("<div class='KJajaxUpload_Body'/>");
var divLeft = $("<div class='KJajaxUpload_Left'/>");
var divRight = $("<div class='KJajaxUpload_Right'/>");
var uploadButton = $("<input type='button' class='KJajaxUpload_Button' value='Select File' />");
if (options.Text) {
uploadButton.val(options.Text);
}
uploadButton.click(function () {
SelectFiles(target);
})
uploadButton.css({
width: 80
})
if (options.Available) {
uploadButton.prop("disabled", false);
} else {
uploadButton.prop("disabled", true);
}
divUploadBody.css({
"overflow": "hidden"
})
divLeft.css({
float: "left",
width: "100%"
})
divRight.css({
float: "left",
"margin-left": " -20px"
})
_that.append(divClear);
divLeft.append(uploadButton);// 左 button
divLeft.append("<font style='font-size:12px;color:red;margin-left:2px;'>可多选</font>")
divUploadBody.append(divLeft);// 左
divUploadBody.append(divRight);// 右 文件列表
_that.append(divUploadBody);
return _that;
}
/// 创建蒙版
function CreateMark(target) {
var mark;
var width = $(document.body).width() / 2 - 200;
mark = $("<div>");
mark.css({
width: "100%",
height: "100%",
position: "fixed",
left: 0,
top: 0,
opacity: 0.5,
"z-index": 8,
"background-color": "#EFEFF2",
"display": "none"
});
var contentText = $("<div class='KJajaxUpload_upload_wrapper'>");
contentText.html("文件上传中,请稍后...");
contentText.css({
"text-align": "center",
width: "400px",
"padding-bottom": "50px",
"z-index": 9,
position: "fixed",
left: width + "px",
"top": "50%",
"background-color": "white",
"display": "none"
})
contentText.appendTo($("body"));
mark.appendTo($("body"));
return mark;
}
///创建进度条
function CreateUploadBar(target) {
var contentText = $(".KJajaxUpload_upload_wrapper");
var fileDiv = $(target);// $.data(target, "KJajaxUpload").FileDiv;
var FileList = fileDiv.find(".fileuploadlist.newfilelist");
$.each(FileList, function (i) {
var fileName = $(this).attr("filename");
var divid = $(this).attr("id");
var proressDiv = $("<div id='KJajaxUpload_progress_" + i + "' />");
var fileNameLable = $("<span >" + fileName + "</span>");
var barDiv = $("<div id='KJajaxUpload_bar_" + divid + "' name='KJajaxUpload_bar_" + fileName + "'/>");
barDiv.css({
width: "350px",
"margin-left": "20px",
height: "22px",
border: "1px solid black ",
"line-height": "22px"
})
var barText1 = $("<div class='KJajaxUpload_progresstext'/>");
barText1.css({
"text-align": "center",
"position": "absolute",
width: "350px"
});
barText1.html("0%");
var barText2 = $("<div class='KJajaxUpload_progresstext'/>");
barText2.css({
"text-align": "center",
width: "350px",
"background-color": "#ffe48d"
});
barText2.html("0%");
var barValue = $("<div class='KJajaxUpload_progressvalue'>");
barValue.css({
position: "relative",
overflow: "hidden",
width: "0px"
})
barValue.append(barText2);
barDiv.append(barText1);
barDiv.append(barValue);
proressDiv.append(fileNameLable);
contentText.append(proressDiv);
contentText.append(barDiv);
});
}
function ChangeProcess(filename, evt) {
var loaded = evt.loaded; //已经上传大小情况 
var tot = evt.total; //附件总大小 
var per = Math.floor(100 * loaded / tot); //已经上传的百分比 
var that = $("[name='KJajaxUpload_bar_" + filename + "']");
that.find('div.KJajaxUpload_progressvalue').css("width", per + "%");
that.find('div.KJajaxUpload_progresstext').html(per + "%");
}
///选择文件
function SelectFiles(target) {
var options = $.data(target, "KJajaxUpload").Options;
var deleteButtonUrl = options.deleteButtonUrl;
var ele = $("<input type='file'/>");
ele.prop("multiple", options.multiple !== false);
ele.hide();
ele.change(function (e) {
var exist = false;
var files = e.target.files;
var filenames = GetalreadyExistFileNames(target);
for (var item in files) {
var file = files[item];
if ($.inArray(file.name, filenames) > -1) {
exist = true;
break;
}
}
if (!exist) {
var ul = $("<ul style='margin:0px;'/>");
for (var i = 0, n = files.length; i < n; i++) {
var deletebutton = $("<img src='" + deleteButtonUrl + "' onmouseover='changeCursor(this)' class='deleteBtn' />");
deletebutton.click(function () {
deleteSelfAndFile(this);
})
var guid = new GUID().New();
var li = $('<li class="fileuploadlist newfilelist" id="' + guid + '" filename="' + files[i].name + '" >' + files[i].name + ' (' + bytesToSize(files[i].size) + ' )</li>');
li.append(deletebutton);
ul.append(li);
}
$(target).find(".KJajaxUpload_Right").append(ul);
options.onChange.call(this, e);
} else {
alert("文件名重复");
ele.remove();
return
}
});
$(target).append(ele);
ele.click();
}
/// 获取已经存在的文件名列表
function GetalreadyExistFileNames(target) {
var that = $(target);
var fileExists = that.find(".fileuploadlist");
var fileNames = [];
/// 还存在的文件列表
fileExists.each(function () {
var filename = $(this).attr("filename");
if ($.inArray(filename, fileNames) == -1) {
fileNames.push(filename);
}
})
return fileNames;
}
/// 上传文件
function UploadFiles(target) {
var that = $(target);
var fileInputs = that.find(":file");
var options = $.data(target, "KJajaxUpload").Options;
var deleteButtonUrl = options.deleteButtonUrl;
var onUploaded = options.onUploaded;
if (fileInputs.length > 0) {
var total = 0;
var uploaded = 0;
var reponses = [];
var mark = $.data(target, "KJajaxUpload").Mark;
var markcontent = $(".KJajaxUpload_upload_wrapper");
mark.show();
markcontent.show();
CreateUploadBar(target);
var fileExists = that.find(".fileuploadlist");
var fileNames = [];
/// 还存在的文件列表
fileExists.each(function () {
var filename = $(this).attr("filename");
if ($.inArray(filename, fileNames) == -1) {
fileNames.push(filename);
}
})
for (var i = 0; i < fileInputs.length; i++) {
var fileinput = fileInputs[i];
var files = fileinput.files;
if (files.length > 0) {
for (var j = 0, n = files.length; j < n; j++) {
if ($.inArray(files[j].name, fileNames) > -1) {
total++;
var filename = files[j].name;
var paramData = options.formData;
var data = new FormData();
data.append("uploadedfile[" + j + "]", files[j]);
if (paramData != null) {
for (var k in paramData) {
data.append(k, paramData[k]);
}
}
var xhr = CreateXMLHttpRequest(target);
xhr.upload.addEventListener("progress",
function (data) {
return function (e) {
ChangeProcess(data, e);
}
}(filename), false);
xhr.upload.addEventListener("loadend", function () {
}, false);
xhr.upload.addEventListener("load", function () {
uploaded++;
}, false);
xhr.onreadystatechange = function () {
if (this.readyState == 4) {// 4 = "loaded"
if (this.status == 200) {// 200 = OK 
reponses.push(this.responseText);
if (uploaded == $.data(target, "KJajaxUpload").TotalFiles) {
var HasUploaded = that.find(".KJajaxUpload_HasUploaded");
var ul = $("<ul style='margin:0px;'/>");
for (var t = 0; t < reponses.length; t++) {
var files = JSON.parse(reponses[t]);
for (var i = 0, n = files.length; i < n; i++) {
var deletebutton = $("<img src='" + deleteButtonUrl + "' onmouseover='changeCursor(this)' class='deleteBtn' />");
deletebutton.click(function () {
deleteSelfAndFile(this);
})
var guid = new GUID().New();
var li = $('<li class="fileuploadlist" id="' + guid + '" filename="' + files[i].Name + '" filepath="' + files[i].FilePath + '" ><a target="_blank" href="' + files[i].FileUrl + '">' + files[i].Name + '</a> </li>');
li.append(deletebutton);
ul.append(li);
}
}
that.find(".KJajaxUpload_Right").empty();
HasUploaded.append(ul);
fileInputs.remove();
Uploaded(target);
var data = GetAlreadyUploadedFiles(target);
onUploaded.call(null, data);
}
}
else {
alert("Problem retrieving XML data");
}
}
};
xhr.open("POST", options.url, true);
xhr.send(data);
}
}
var state = $.data(target, "KJajaxUpload");
state.TotalFiles = total;
$.data(this, "KJajaxUpload", state);
}
}
} else {
var data = GetAlreadyUploadedFiles(target);
onUploaded.call(null, data);
}
return that;
}
/// 上传完毕
function Uploaded(target) {
alert("文件上传完毕");
var mark = $.data(target, "KJajaxUpload").Mark;
var markcontent = $(".KJajaxUpload_upload_wrapper");
mark.hide();
markcontent.hide();
var that = $(target);
var fileInputs = that.find(":file");
fileInputs.remove();
}
///初始化已有的数据
function AlreadFiles(target, options) {
var that = $(target);
var deleteButtonUrl = options.deleteButtonUrl;
var files = options.AlreadFiles;
var HasUploaded = that.find(".KJajaxUpload_HasUploaded");
if (files.length > 0) {
var ul = $("<ul style='margin:0px;'/>");
for (var i = 0, n = files.length; i < n; i++) {
var deletebutton = $("<img src='" + deleteButtonUrl + "' onmouseover='changeCursor(this)' class='deleteBtn' />");
deletebutton.click(function () {
deleteSelfAndFile(this);
})
var pos = files[i].lastIndexOf("\\");
var filepos = files[i].lastIndexOf("uploadFile");
var reg = /[\\\/]/g;
var filePath = files[i];
var fileUrl = files[i].substr(filepos).replace(reg, '/');
var fileName = files[i].substr(pos + 1);
fileName = fileName.substr(fileName.lastIndexOf("_S_") + 3);
var guid = new GUID().New();
var li = $('<li class="fileuploadlist" id="' + guid + '" filename="' + fileName + '" filepath="' + filePath + '" ><a target="_blank" href="' + fileUrl + '">' + fileName + '</a> </li>');
li.append(deletebutton);
ul.append(li);
}
HasUploaded.append(ul);
}
}
function GetAlreadyUploadedFiles(target) {
var that = $(target);
var HasUploaded = that.find(".KJajaxUpload_HasUploaded li");
var datas = [];
HasUploaded.each(function () {
var data = {};
data.name = $(this).attr("filename");
data.filepath = $(this).attr("filepath");
data.fileurl = $(this).find("a").attr("href");
datas.push(data);
})
return datas;
}
$.fn.KJajaxUpload = function (options, param) {
var that = this;
if (typeof options == "string") {
var method = $.fn.KJajaxUpload.Methods[options];
if (method) {
return method(this, param);
}
}
options = options || {};
return this.each(function () {
var that = this;
var state = $.data(this, "KJajaxUpload");
if (state) {
$.extend(state.Options, options);
} else {
var _options = $.extend({}, $.fn.KJajaxUpload.Default, options);
InitFileDiv(this, _options);
AlreadFiles(this, _options);
state = $.data(this, "KJajaxUpload", {
Options: _options,
Mark: CreateMark(this),
TotalFiles: 0
});
}
})
}
$.fn.KJajaxUpload.Default = {
url: '/Ashx/UploadFilesHandler.ashx?r=' + Math.random(),
formData: {},//要传递的参数
Text: "选择文件",
ContinueAddText: "继续添加",
multiple: true,
AlreadFiles: [],// 初始化已经存在的文件
Available: true,// 可用的
deleteButtonUrl: '/Style/images/delete.jpg',
onInit: function () { },
onChange: function () { },
onUploaded: function () { }// 文件上传完毕后的回调函数
};
$.fn.KJajaxUpload.Methods = {
options: function (jq) {
return $.data(jq[0], "KJajaxUpload").Options;
},
upload: function (jq) {
return UploadFiles(jq[0]);
}
};
})(jQuery)

后端代码

/// <summary>
/// UploadFilesHandler 的摘要说明
/// </summary>
public class UploadFilesHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
List<FileReponse> list = new List<FileReponse>();
string filePath = System.AppDomain.CurrentDomain.BaseDirectory.ToString() + @"uploadFile\" + DateTime.Now.Year.ToString() + @"\" + DateTime.Now.Month.ToString() + @"\" + DateTime.Now.Day.ToString() + @"\" + System.Web.HttpUtility.UrlDecode(context.Request.Params["userName"].ToString()) + @"\";
if (context.Request.Files.Count > 0)
{
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
try
{
foreach (string files in context.Request.Files)
{
HttpPostedFile upfile = context.Request.Files[files];
int bufferSize = 1024 * 50;//50K
string _guid = Guid.NewGuid().ToString().Replace("-", "");
byte[] buffer = new byte[bufferSize];
int currentCounts = 0;//
long totalLength = upfile.ContentLength;
string name = upfile.FileName.Substring(upfile.FileName.LastIndexOf("\\") + 1);
string fileName = filePath + _guid + "_S_" + name;
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
while (currentCounts < totalLength)
{
int bytes = upfile.InputStream.Read(buffer, 0, bufferSize);
fs.Write(buffer, 0, bytes);
//Thread.Sleep(1);//0.001s
currentCounts += bytes;
}
}
FileReponse item = new FileReponse();
item.Name = name;
item.FilePath = fileName;
int filepos = item.FilePath.LastIndexOf("uploadFile");
item.FileUrl = item.FilePath.Substring(filepos);
list.Add(item);
}
}
catch (Exception ex)
{
}
}
string reponse = JsonConvert.SerializeObject(list);
context.Response.Write(reponse);
//context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");
}
public bool IsReusable
{
get
{
return false;
}
}
}
internal class FileReponse
{
public string Name { get; set; }
public string FilePath { get; set; }
public string FileUrl { get; set; }
}

使用:

var config = {};
config.formData = formData;
if (!HasTheRight("HDComplaintsArea")) {
config.Available = false;
}
if (record.Attachments) {
config.AlreadFiles = record.Attachments;
}
config.onUploaded = function (data) {
save(data);
}
$("#filediv").KJajaxUpload(config);
$("#btnSave").click(function () {
$("#filediv").KJajaxUpload("upload");
})
function save(data) {
fields.Attachments = [];
for (var i = 0; i < data.length; i++) {
fields.Attachments.push(data[i].filepath);
} 
fields.Attachments = JSON.stringify(fields.Attachments);
}

以上所述是小编给大家介绍的jQuery多文件异步上传带进度条实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Javascript 相关文章推荐
基于jquery的9行js轻松实现tab控件示例
Oct 12 Javascript
基于js实现微信发送好友如何分享到朋友圈、微博
Nov 30 Javascript
jQuery遍历json的方法分析
Apr 16 Javascript
AngularJs $parse、$eval和$observe、$watch详解
Sep 21 Javascript
详解AngularJS验证、过滤器、指令
Jan 04 Javascript
Node.JS中事件轮询(Event Loop)的解析
Feb 25 Javascript
基于 Vue 的树形选择组件的示例代码
Aug 18 Javascript
详解如何webpack使用DllPlugin
Sep 30 Javascript
vue中的过滤器实例代码详解
Jun 06 Javascript
vue axios重复点击取消上一次请求封装的方法
Jun 19 Javascript
详解vue+axios给开发环境和生产环境配置不同的接口地址
Aug 16 Javascript
解决vue的过渡动画无法正常实现问题
Oct 31 Javascript
AngularJS指令详解及示例代码
Aug 16 #Javascript
AngularJS教程之简单应用程序示例
Aug 16 #Javascript
AngularJS教程之MVC体系结构详解
Aug 16 #Javascript
超实用的javascript时间处理总结
Aug 16 #Javascript
AngularJS教程之环境设置
Aug 16 #Javascript
JavaScript中获取时间的函数集
Aug 16 #Javascript
利用Javascript实现BMI计算器
Aug 16 #Javascript
You might like
摩卡咖啡
2021/03/03 咖啡文化
PHP 的ArrayAccess接口 像数组一样来访问你的PHP对象
2010/10/12 PHP
解析php中反射的应用
2013/06/18 PHP
PHP-Fcgi下PHP的执行时间设置方法
2013/08/02 PHP
PHP实现批量修改文件名的方法示例
2019/09/18 PHP
从新浪弄下来的全屏广告代码 与使用说明
2007/03/15 Javascript
通过jQuery源码学习javascript(一)
2012/12/27 Javascript
得到form下的所有的input的js代码
2013/11/07 Javascript
nodejs实现黑名单中间件设计
2014/06/17 NodeJs
JS烟花背景效果实现方法
2015/03/03 Javascript
javascript实现随时变化着的背景颜色
2015/04/02 Javascript
基于jQuery实现在线选座之高铁版
2015/08/24 Javascript
详解vue express启动数据服务
2017/07/05 Javascript
vue 项目如何引入微信sdk接口的方法
2017/12/18 Javascript
基于IView中on-change属性的使用详解
2018/03/15 Javascript
Vue中Quill富文本编辑器的使用教程
2018/09/21 Javascript
浅谈JS和jQuery的区别
2019/03/27 jQuery
浅谈Vue.set实际上是什么
2019/10/17 Javascript
vue学习笔记之slot插槽用法实例分析
2020/02/29 Javascript
[46:49]完美世界DOTA2联赛PWL S3 access vs Rebirth 第二场 12.19
2020/12/24 DOTA
python实现可以断点续传和并发的ftp程序
2016/09/13 Python
Python 文件操作的详解及实例
2017/09/18 Python
Python 函数返回值的示例代码
2019/03/11 Python
Python分支语句与循环语句应用实例分析
2019/05/07 Python
python3使用GUI统计代码量
2019/09/18 Python
python sorted方法和列表使用解析
2019/11/18 Python
tensorflow中tf.slice和tf.gather切片函数的使用
2020/01/19 Python
HTML5中使用postMessage实现两个网页间传递数据
2016/06/22 HTML / CSS
会展策划与管理专业求职信
2014/06/09 职场文书
班主任与学生安全责任书
2014/07/25 职场文书
安全目标管理责任书
2014/07/25 职场文书
民政工作个人总结
2015/02/28 职场文书
六一儿童节新闻稿
2015/07/17 职场文书
python​格式化字符串
2022/04/20 Python
python实现双链表
2022/05/25 Python
Java中的Kotlin 内部类原理
2022/06/16 Java/Android