Layui多图上传至后端.NET版

Layui的多图上传这方面前端做得还是很到位,今天我们就来使用.NET实现多图上传的接口,各位可以改一改代码拿去用

害 废话不多说先上HTML

<div class="modal-content">
	<div class="modal-header">
		<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
		<h4 class="modal-title">上传图片</h4>
	</div>
	<div class="modal-body">
		<div class="layui-upload">
			<button type="button" class="layui-btn layui-btn-normal" id="testList">选择多文件</button><input class="layui-upload-file" type="file" accept="" name="file" multiple="">
			<div class="layui-upload-list">
				<table class="layui-table">
					<thead>
						<tr>
							<th>文件名</th>
							<th>大小</th>
							<th>状态</th>
							<th>操作</th>
						</tr>
					</thead>
					<tbody id="ProImgByList">
					</tbody>
				</table>
			</div>
			<button type="button" class="layui-btn" id="testListAction">开始上传</button>
		</div>
	</div>
	<div class="modal-footer">
		<button type="button" class="btn dark btn-outline" data-dismiss="modal">关闭</button>
	</div>
</div>

来到了 javascript,设置接口添加并监听事件

<script>
    layui.use('upload', function () {
        var $ = layui.jquery
            , upload = layui.upload;

        //多文件列表示例
        var ProImgByList = $('#ProImgByList')
            , uploadListIns = upload.render({
                elem: '#testList'
                , url: '/admin/ashx/upByProImages.ashx' //接口,我们这里定义成了 ashx
                , accept: 'file'
                , multiple: true
                , auto: false
                , bindAction: '#testListAction' //按扭绑定
                , choose: function (obj) {
                    var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                    //读取本地文件
                    obj.preview(function (index, file, result) {
                        var tr = $(['<tr id="upload-' + index + '">'
                            , '<td>' + file.name + '</td>'
                            , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                            , '<td>等待上传</td>'
                            , '<td>'
                            , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                            , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                            , '</td>'
                            , '</tr>'].join(''));

                        //单个重传
                        tr.find('.demo-reload').on('click', function () {
                            obj.upload(index, file);
                        });

                        //删除
                        tr.find('.demo-delete').on('click', function () {
                            delete files[index]; //删除对应的文件
                            tr.remove();
                            uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值,以免删除后出现同名文件不可选
                        });

                        ProImgByList.append(tr);
                    });
                }
                , done: function (res, index, upload) {
                    if (res.result == 1) { //上传成功
                        var tr = ProImgByList.find('tr#upload-' + index)
                            , tds = tr.children();
                        tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                        tds.eq(3).html(''); //清空操作
                        return delete this.files[index]; //删除文件队列已经上传成功的文件
                    }
                    this.error(index, upload);
                }
                , error: function (index, upload) {
                    var tr = ProImgByList.find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(2).html('<span style="color: #FF5722;">上传失败[检查文件名及文件格式]</span>');
                    tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
                }
            });

    });
</script>

来到了后端C#/.NET语言的位置 我还是比较喜欢ASHX(一般处理程序)

    /// <summary>
    /// upfiles 的摘要说明
    /// </summary>
    public class upByProImages
    {
        //配置图片存放的路径,童鞋们可以修改掉,换成固定也的行,节点
        const string AppSetingName = "UpByProImgFile";

        public void ProcessRequest(HttpContext context)
        {
            #region 验证是否成功登录 

            if (false) // 如在后端开启严谨写法,如没有请删除这段判断 -- !IsAdminLogin()
            {
                JsonResult(context, -99, "管理员未登陆");
            }
            #endregion
            else
            {

                HttpPostedFile files = context.Request.Files["file"];
                if (files == null)
                    JsonResult(context, 0, "未找到文件!");
                string path = context.Server.MapPath(Evan.Common.CommFun.GetAppSetting(AppSetingName));  // Evan.Common.CommFun.GetAppSetting 这个方法读取存放路径的,当然这个是不是System自带的。

                dynamic dyResult = UpLoadFile(files, path);

                if (dyResult != null && dyResult.result == 1)
                {
                    JsonResult(context, 1, "上传成功!");
                }
                else
                {
                    JsonResult(context, 0, "上传失败!");
                }
            }

        }

        public dynamic UpLoadFile(HttpPostedFile files, string path, int _isWater = 0)
        {
            dynamic Result_Ob = new { result = 0, returnval = "上传失败!" };

            try
            {
                if (Directory.Exists(path))
                {
                    string es = Path.GetExtension(files.FileName);
                    if (es.ToUpper().StartsWith(".JPG") || es.ToUpper().StartsWith(".PNG"))
                    {
                        string fileurl = path + files.FileName; 

                        if (!File.Exists(fileurl)) //判断是有该文件
                        {
                            files.SaveAs(fileurl);

                            if (File.Exists(fileurl)) // 可加一些其它安全检测啥的,检测图片安全,如果各位需要现成可以面向百度:IsSecureUpfilePhoto()
                            {
                                //这里可以执行一些其它的操作,比如更新数据库
                                Result_Ob = new { result = 1, returnval = fileurl };
                            }
                            else
                            {
                                File.Delete(fileurl);
                                Result_Ob = new { result = 0, returnval = "上传失败!此文件为恶意文件" };
                            }
                        }

                    }
                }

            }
            catch
            {

            }
            return Result_Ob;
        }
        
        /// <summary>
        /// 输出json结果 返回2个值 result (输出succes的值)   returnval (输出str的值)
        /// </summary>
        /// <param name="context"></param>
        /// <param name="success">是否操作成功,0表示失败;1表示成功</param>
        /// <param name="str">输出字符串</param>
        protected void JsonResult(HttpContext context, int success, string str)
        {
            context.Response.Write("{\"result\" :\"" + success.ToString() + "\",\"returnval\" :\"" + str + "\"}");
            context.Response.End();
        }
    }
posted @ 2020-05-22 14:34  baicexxqtd  阅读(781)  评论(3编辑  收藏  举报