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多文件异步上传带进度条实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!

(0)

相关推荐

  • jQuery实现文件上传进度条特效

    上传进度条通常是由前面jquery加后端了脚本器脚本来实现了,今天我们介绍的是一款基本php+jQuery实现文件上传进度条效果的例子,具体细节如下. 最近呢,一个项目做一个进度条的效果出来,这个之前还真没做过.刚好这周没什么东西了,就拿这个来充一下数吧. 文件上传,得先准备一个"按钮": 这个看上去还是不错的吧,实现也是很简单的: <span class="upload-span">开始上传文件</span> <button>太

  • jQuery监听文件上传实现进度条效果的方法

    原理: 给XMLHttpRequest对象的upload属性绑定onprogress方法监听上传过程 var xhr=new XMLHttpRequest(); xhr.upload.onprogress=function(e){} 因为jQuery默认使用的XMLHttpRequest对象是内部生成的无法直接给jq的xhr绑定onprogress方法 所以只要给jQuery重新生成一个绑定了onprogress的XMLHttpRequest对象即可实现 首先封装一个方法 传入一个监听函数 返回

  • 基于Jquery插件Uploadify实现实时显示进度条上传图片

    先了解了解Uploadify,具体内容如下 Uploadify是一个简单易用的多文件上传方案.作为一个Jquery插件,Uploadify使用简单,并具有高度的定制性. Uploadify特性: Uploadify简单说来,是基于Jquery的一款文件上传插件.它的功能特色总结如下: 1).支持单文件或多文件上传,可控制并发上传的文件数 2).在服务器端支持各种语言与之配合使用,诸如PHP,.NET,Java-- 3).通过参数可配置上传文件类型及大小限制 4).通过参数可配置是否选择文件后自动

  • jQuery实现简单的文件上传进度条效果

    本文实例讲述了jQuery实现文件上传进度条效果的代码.分享给大家供大家参考.具体如下: 运行效果截图如下: 具体代码如下: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>upload</title> <link rel="stylesheet" type="text/css" href=&quo

  • 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)

  • asp.net web大文件上传带进度条实例代码

    复制代码 代码如下: using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using Syste

  • ajax 异步上传带进度条视频并提取缩略图

    最近在做一个集富媒体功能于一身的项目.需要上传视频.这里我希望做成异步上传,并且有进度条,响应有状态码,视频连接,缩略图. 服务端响应 { "thumbnail": "/slsxpt//upload/thumbnail/fdceefc.jpg", "success": true, "link": "/slsxpt//upload/video/fdceefc.mp" } 并且希望我的input file控件不

  • Jquery Uploadify多文件上传带进度条且传递自己的参数

    复制代码 代码如下: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="UpLoad.aspx.cs" Inherits="UploadifyDemo_UpLoad" %> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" r

  • asp.net mvc 实现文件上传带进度条的思路与方法

    前言 文件上传与下载的操作在实际项目中经常是很重要的一个内容,在使用ASP.NET Web Form的时候我们可以使用诸多的服务器控件,FileIpload就是其中之一,但是在ASP.NET不建议使用那些服务器控件,因为那样违反三层架构原则.最近参考网络资料,学习了ASP.NET MVC如何上传文件. 而这篇文章主要重点是asp.net mvc 实现文件上传带进度条,下面来一起看看吧. 实现思路 ajax异步上传文件,且开始上传文件的时候启动轮询来实时获取文件上传进度.保存进度我采用的是memc

  • jquery-file-upload 文件上传带进度条效果

    jQuery File Upload 是一个Jquery图片上传组件,支持多文件上传.取消.删除,上传前缩略图预览.列表显示图片大小,支持上传进度条显示:支持各种动态语言开发的服务器端. 效果图如下所示: html 部分 <div style="line-height:34px;margin-top:20px;"> <label style="float: left;font-size:14px">上传文件:</label> &l

  • 基于fileUpload文件上传带进度条效果的实例(必看)

    文件上传过程中,如果我们能看到进度条会更好,实现思路是服务器端用监听器实时监听进度并存入session,客户端异步请求服务器端获得上传进度,并进行效果渲染. 效果图: 服务器端servlet: public class UploadServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException

  • Jquery Uploadify上传带进度条的简单实例

    复制代码 代码如下: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="UpLoad.aspx.cs" Inherits="UploadifyDemo_UpLoad" %> <html xmlns="http://www.w3.org/1999/xhtml"><head id="Head1" ru

  • 基于Ajax技术实现文件上传带进度条

    1.概述 在实际的Web应该开发或网站开发过程中,经常需要实现文件上传的功能.在文件上传过程中,经常需要用户进行长时间的等待,为了让用户及时了解上传进度,可以在上传文件的同时,显示文件的上传进度条.运行本实例,如图1所示,访问文件上传页面,单击"浏览"按钮选择要上传的文件,注意文件不能超过50MB,否则系统将给出错误提示.选择完要上传的文件后,单击"提交"按钮,将会上传文件并显示上传进度. 2.技术要点 主要是应用开源的Common-FileUpload组件来实现分

  • 浅谈struts1 & jquery form 文件异步上传

    1.概述 还在用struts1?是的,在地球的没写地方,落后的生产方式还在运转(老项目). 从 继承org.apache.struts.action.Action, 继承org.apache.struts.action.ActionForm开始吧 2. 代码 2.1 html页面 <html> <head> <title>网页上传</title> </head> <body> <center> <h1>本地文件

随机推荐