使用 layui 的模块化加载(layui.js),需修改modules/upload.js,修改 p.prototype.upload 方法下 layui.each 内的 i.ajax 方法,添入代码如下红框内所示
xhr: l.xhr(function (e) {
var percent = Math.floor((e.loaded / e.total) * 100);
l.progress(percent);
}),
监听 xhr 也就是 XMLHttpRequest ,ajax的核心技术就是这个!
参考:https://www.cnblogs.com/xiaohuochai/p/6036475.html
前端界面
<head>
<title>upload上传</title>
<link href="Content/layui/css/layui.css" rel="stylesheet" />
</head>
<body>
<div class="layui-form">
<div class="layui-form-item layui-col-lg6">
<label class="layui-form-label">上传文件</label>
<div class="layui-input-block">
<div class="layui-upload-list">
<!-- 文件选择框 -->
<div class="layui-upload-drag UploadBusi">
<div lay-filter="UploadToolsOne">
<i class="layui-icon" style="font-size: 50px !important;"></i>
<p>点击上传,或将文件拖拽到此处</p>
</div>
<span id="demo2" class="layui-form-label layui-hide" style="width: auto;"></span>
<img id="demo1" class="layui-upload-img layui-hide" style="height: 107px; width: 196px;" />
</div>
<!-- 进度条样式 -->
<div class="layui-progress layui-progress-big" lay-showpercent="true" lay-filter="demo">
<div class="layui-progress-bar layui-bg-red" lay-percent="0%"></div>
</div>
</div>
<div class="layui-inline">
<input id="uploadPicOne" type="button" class="layui-btn" value="上传" />
</div>
</div>
</div>
</div>
<script src="Content/layui/layui.js"></script>
</body>
附带上 xhr 监听方法显示 progress 进度条的 js 代码,包含监听函数、文件上传实例,以通过文件保存接口实现文件上传功能。
<script>
layui.use(['form', 'upload', 'element', 'layer', 'jquery'], function () {
var upload = layui.upload, $ = layui.jquery, element = layui.element, layer = layui.layer;
//创建监听函数
var xhrOnProgress = function (fun) {
xhrOnProgress.onprogress = fun; //绑定监听
//使用闭包实现监听绑
return function () {
//通过$.ajaxSettings.xhr();获得XMLHttpRequest对象
var xhr = $.ajaxSettings.xhr();
//判断监听函数是否为函数
if (typeof xhrOnProgress.onprogress !== 'function')
return xhr;
//如果有监听函数并且xhr对象支持绑定时就把监听函数绑定上去
if (xhrOnProgress.onprogress && xhr.upload) {
xhr.upload.onprogress = xhrOnProgress.onprogress;
}
return xhr;
}
}
//执行实例
var uploadInit = upload.render({
elem: '.UploadBusi' //绑定元素
, method: 'post'
, url: '/handle/layer_upload_busi.ashx' //上传接口
, accept: 'file'
, auto: false //选择文件后不自动上传
, bindAction: '#uploadPicOne' //指向一个按钮触发上传
, xhr: xhrOnProgress //传入监听函数!important
, progress: function (value) {
console.log("进度:" + value + '%');
element.progress('demo', value + '%');
}
, choose: function (obj) {
element.progress('demo', '0%');
//预读本地文件示例,不支持ie8
var uploadFileInput = $(".layui-upload-file").val();
var uploadFileName = uploadFileInput.split("\\");
$('#demo2').text(uploadFileName[uploadFileName.length - 1]);
$('#demo2').removeClass("layui-hide");
$('div[lay-filter="UploadToolsOne"]').addClass("layui-hide");
$('#uploadPicOne').removeClass("layui-hide");
}
, before: function (obj) {
layer.load();
}
, done: function (res, index, upload) {
//上传完毕回调
if (res.code == "0") {
if (res.msg.split(':')[0] == "OK") {
$('#demo1').attr('src', res.src);
$('#uploadPicOne').addClass("layui-hide");
layer.msg(res.msg.split(':')[1], { icon: 1, time: 2000, shift: 1 });
}
if (res.msg.split(':')[0] == "Error") {
layer.msg(res.msg.split(':')[1], { icon: 5, time: 2000, shift: 6 });
}
}
layer.closeAll('loading'); //关闭loading
}
, error: function (res) {
//请求异常回调
//layer.msg("系统异常错误!", { icon: 5, time: 2000, shift: 6 });
element.progress('demo', '0%');
layer.closeAll('loading'); //关闭loading
}
});
});
</script>
调用上传文件接口 /handle/layer_upload_busi.ashx,此处使用的是一般处理程序上传文件,可依据个人情况使用不同的后端接口。
///
/// layer_upload_busi 的摘要说明
///
public class layer_upload_busi : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string pictureName = "", OK = "", Error = "";
string FilesName = context.Request.Files[0].FileName;//获取客户端上文件的完全限定名称
string PathName = "";
int idx1 = FilesName.LastIndexOf(".");
string UserId = "admin";//应进行身份认证,此处暂时赋值处理
if (UserId != "")
{
try
{
HttpFileCollection hfc = context.Request.Files;
if (hfc.Count > 0)
{
HttpPostedFile hpf = hfc[0];
if (hpf.ContentLength > 0)
{
string comId = DateTime.Now.ToString("yyyyMMddhhmmss"); //实际生产中会使用用户的唯一标识符来作为识别码
string suffix1 = FilesName.Substring(idx1);//获得上传的图片的后缀名
pictureName = comId;
string path = context.Server.MapPath("../userupload/");
PathName = path + pictureName + suffix1;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
hfc[0].SaveAs(path + pictureName + suffix1);//保存已上载的内容
OK = "上传成功!";
}
else{ Error = "文件获取错误"; }
}
else{ Error = "文件获取错误"; }
}
catch (Exception ex){ Error = "系统错误:" + ex.Message; }
}
else{ Error = "登录信息失效,请重新登录!"; }
StringWriter sw = new StringWriter();
JsonWriter writer = new JsonTextWriter(sw);
writer.WriteStartObject();
writer.WritePropertyName("code"); writer.WriteValue(0);
writer.WritePropertyName("msg");
if (OK != ""){ writer.WriteValue("OK:" + OK); }
else { writer.WriteValue("Error:" + Error); }
writer.WritePropertyName("src");
writer.WriteValue(PathName);
writer.WriteEndObject();
writer.Flush();
string jsonText = sw.GetStringBuilder().ToString();
context.Response.Write(JsonConvert.SerializeObject(jsonText));
//{"code":0,"msg":"OK:上传成功!","src":"E:\\…\\userupload\\20191018054139-1.jpg"}
}
public bool IsReusable
{
…
}
}
运行效果:
选择图片后效果:
点击上传成功后效果:
代码比较陈旧,考虑不周的地方,欢迎指正。
参考:https://blog.csdn.net/qq_38423105/article/details/81612009