layui-多个文件同时上传

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UploadFiles.aspx.cs" Inherits="TCIQDOA.FilesManager.View.UploadFiles" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>上传文件</title>
	<script src="../../javascript/jquery-1.9.1.min.js"></script>
	<link href="../../javascript/layui-v2.3.0/css/layui.css" rel="stylesheet" />
	<script src="../../javascript/layui-v2.3.0/layui.js"></script>
	<script src="../../javascript/vue/vue.js"></script>
	<style>
		.Upload-ul {
			background-color: rgba(172, 172, 172, 0.137);
			padding: 10px 10px;
			clear: both;
		}

			.Upload-ul .file-file {
				position: relative;
				margin-top: 5px;
				margin-bottom: 5px;
				margin-left:0.5%;
			    margin-right:0.5%;
				padding: 10px;
				padding-right: 50px;
				background-color: rgba(172, 172, 172, 0.1);
				border: 1px rgba(172, 172, 172, 0.1) solid;
				border-radius: 4px;
				-webkit-user-select: none;
				-moz-user-select: none;
				-ms-user-select: none;
				user-select: none;
			}

				.Upload-ul .file-file a {
					height: 20px;
					line-height: 20px;
				}

				.Upload-ul .file-file button {
					position: absolute;
					right: 10px;
					top: 50%;
					transform: translate(0%, -50%);
					z-index: 100;
					padding: 1px 2px 0px 4px;
					background-color: rgba(172, 172, 172, 0.0);
					color: gray;
				}

		.Upload-layui-btn:hover {
			color: red;
		}

		.Upload-ul .file-image {
			position: relative;
			margin-top: 5px;
			margin-bottom: 5px; 
			padding:5px;
			background-color: rgba(172, 172, 172, 0.1);
			border: 1px rgba(172, 172, 172, 0.1) solid;
			border-radius: 4px;
			-webkit-user-select: none;
			-moz-user-select: none;
			-ms-user-select: none;
			user-select: none;
			float: left;
			margin-left:0.5%;
			margin-right:0.5%;
			width: 32.333%;
			box-sizing: border-box;
		} 
			.Upload-ul .file-image img {
				width: 80px;
				height:80px;
			}
			.Upload-ul .file-image button {
				position: absolute;
				right: 10px;
				top: 50%;
				transform: translate(0%, -50%);
				z-index: 100;
				padding: 1px 2px 0px 4px;
				background-color: rgba(172, 172, 172, 0.0);
				color: gray;
			}
	</style>
	<script>
		var vueUploadFiles;
		$(function () {
			vueUploadFiles = new Vue({
				el: '#VueUploadFiles',
				data: {
					files: [],
					images: [],
				}
			});
			layui.use('upload', function () {
				var upload = layui.upload;
				//执行实例
				var uploadInst = upload.render({
					elem: '#btn_UploadImage',//绑定元素
					url: '../Controller/UploadFiles.ashx',//上传接口
					multiple: 'true',
					accept: "images|file|video|audio",
					exts: 'jpg|png|gif|bmp|jpeg|zip|rar|7z|pdf|doc|docx|xls|xlsx|avi|mp4|rmvb|wmv|txt|pub|pptx|ppt',
					data: {
						cmd: "UploadSomeFiles"
					},
					choose: function (obj) {
						//将每次选择的文件追加到文件队列
						var files = obj.pushFile();
						//预读本地文件,如果是多文件,则会遍历。(不支持ie8/9)
						obj.preview(function (index, file, result) {
							var vuefiles = vueUploadFiles.files;
							var vueimages = vueUploadFiles.images;
							var isExist = false;
							for (var i = 0; i < vuefiles.length; i++) {
								var obj = vuefiles[i];
								if (obj.name == file.name) {
									delete files[index];
									isExist = true;
									break;
								}
							}
							for (var i = 0; i < vueimages.length; i++) {
								var obj = vueimages[i];
								if (obj.name == file.name) {
									delete files[index];
									isExist = true;
									break;
								}
							}
							if (!isExist) {
								if (file.name.getFileType() == "image") {
									vueUploadFiles.images.push({ name: file.name, url: "#", isUpload: false });
								} else {
									vueUploadFiles.files.push({ name: file.name, url: "#", isUpload: false });
								}
							}
						});
					},
					done: function (res) { //上传完毕回调
						if (res.isSuccess == 'true') {
							var files = vueUploadFiles.files;
							var images = vueUploadFiles.images;
							files.forEach(function (obj) {
								if (obj.name == res.name) {
									obj.url = res.url;
									obj.isUpload = true;
									return;
								}
							});
							images.forEach(function (obj) {
								if (obj.name == res.name) {
									obj.url = res.url;
									obj.isUpload = true;
									return;
								}
							});

						}
					},
					error: function () { //请求异常回调
					}
				});
			});
		});
		function deleteFileClick(name) {
			var files = vueUploadFiles.files;
			var images = vueUploadFiles.images;
			for (var i = 0; i < files.length; i++) {
				var obj = files[i];
				if (obj.name == name) {
					files.remove(obj);
					break;
				}
			}
			for (var i = 0; i < images.length; i++) {
				var obj = images[i];
				if (obj.name == name) {
					images.remove(obj);
					break;
				}
			}
		}
		//移除数组中的一个值
		Array.prototype.remove = function (val) {
			var index = this.indexOf(val);
			if (index > -1) {
				this.splice(index, 1);
			}
		};
		String.prototype.getFileType = function () {
			var suffix = this.split('.').pop();
			if (suffix == "jpg" || suffix == "png" || suffix == "gif" || suffix == "bmp" || suffix == "jpeg") {
				return "image";
			} else {
				return "file";
			}
		}
	</script>
</head>
<body>
	<div class="layui-form-item">
		<div class="layui-input-block layui-upload">
			<button type="button" class="layui-btn" id="btn_UploadImage">上传文件</button>
		</div>
	</div>
	<div id="VueUploadFiles" class="Upload-ul">
		<ul>
			<li class="file-file" v-for="file in files"> 
				<a v-bind:href="file.url">{{file.name}}</a>
				<i v-if="!file.isUpload" class="layui-icon layui-anim layui-anim-rotate layui-anim-loop" style="color: green;">&#xe63d;</i>
				<button class="layui-btn layui-btn-xs Upload-layui-btn" v-bind:id="file.name" onclick="deleteFileClick(this.id)">
					<i class="layui-icon">&#x1006;</i>
				</button>
			</li>
		</ul>
		<div class="file-image" v-for="file in images">  
			<img v-bind:src="file.url"/> 
			<i v-if="!file.isUpload" class="layui-icon layui-anim layui-anim-rotate layui-anim-loop" style="color: green;">&#xe63d;</i> 
			<button class="layui-btn layui-btn-xs Upload-layui-btn" v-bind:id="file.name" onclick="deleteFileClick(this.id)">
				<i class="layui-icon">&#x1006;</i>
			</button>  
		</div> 
		<div style="height: 1px; width: 100%; clear: both"></div>
	</div>
</body>
</html>

 

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace TCIQDOA.FilesManager.Controller
{
    /// <summary>
    /// UploadFiles 的摘要说明
    /// </summary>
    public class UploadFiles : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string cmd = context.Request["cmd"];
            switch (cmd)
            {
                case "UploadSomeFiles":
                    {
                        UploadSomeFiles(context);
                        break;
                    }
            }
        } 
        private void UploadSomeFiles(HttpContext context)
        {
            string path = "";
            string name = "";
            try
            {
                int count = context.Request.Files.Count;
                for (int i = 0; i < count; i++)
                {
                    int contentLength = context.Request.Files[i].ContentLength;//文件的大小
                    string contentType = context.Request.Files[i].ContentType;//文件的类型
                    string localPath= context.Request.Files[i].FileName;//文件的本地路径
                    string extension = Path.GetExtension(localPath).ToLower();//文件的后缀
                    string oldName = Path.GetFileName(localPath);
                    string newName = DateTime.Now.ToString("yyyyMMddHHmm_") + oldName.Replace(" ", "_").Replace("&", "_");
                    string filePath = GetPathForSaveFolder(); 
                    string fileSavePath = HttpContext.Current.Server.MapPath(filePath);
                    fileSavePath = fileSavePath + newName;  
                    context.Request.Files[i].SaveAs(fileSavePath);
                    path = filePath + newName;
                    name = oldName;
                }   
            }
            catch (Exception ex)
            {
                context.Response.Write("{\"isSuccess\":\"false\",\"url\":\"上传失败\"}"); 
            }
            finally
            {
                context.Response.Write("{\"isSuccess\":\"true\",\"url\":\"" + path + "\",\"name\":\"" + name + "\"}");
            }  
        } 
        private string GetPathForSaveFolder()
        {
            string path = GetAppPath() + "UploadFile/items/" + DateTime.Now.ToString("yyyy-MM") + "/";
            string fileSavePath = HttpContext.Current.Server.MapPath(path);
            if (!Directory.Exists(fileSavePath))
            {
                Directory.CreateDirectory(fileSavePath);
            } 
            return path;
        }
        private string GetAppPath()
        {
            string applicationPath = HttpContext.Current.Request.ApplicationPath;
            if (!applicationPath.EndsWith("/"))
            {
                applicationPath = applicationPath + "/";
            }
            return applicationPath;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
layui中,可以使用 `upload` 组件来实现文件上传功能。以下是一个简单的示例: HTML代码: ```html <div class="layui-upload"> <button type="button" class="layui-btn" id="test-upload-normal">选择文件</button> <div class="layui-upload-list"> <table class="layui-table"> <thead> <tr><th>文件名</th><th>大小</th><th>状态</th><th>操作</th></tr> </thead> <tbody id="demo-list"></tbody> </table> </div> </div> ``` JavaScript代码: ```javascript //普通图片上传 var uploadInst = layui.upload.render({ elem: '#test-upload-normal', url: '/upload/', accept: 'file', //允许上传文件类型 exts: 'pdf|doc|docx|xls|xlsx', //允许上传文件后缀 size: 2048, //文件大小限制,单位 KB multiple: true, //是否允许多文件上传 done: function(res){ //上传完毕回调 console.log(res); //上传成功后,将文件信息添加到表格中 var tr = '<tr><td>'+ res.filename +'</td><td>'+ res.filesize +'</td><td>上传成功</td><td><button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button></td></tr>'; $('#demo-list').append(tr); }, error: function(){ //请求异常回调 console.log('上传失败'); } }); //删除已上传文件 $(document).on('click', '.demo-delete', function(){ $(this).parents('tr').remove(); }); ``` 在上面的示例代码中,我们使用了 `upload` 组件来实现文件上传功能,并且设置了一些上传参数,如 `accept`、`exts`、`size`等。上传成功后,会调用 `done` 回调函数,在回调函数中将文件信息添加到表格中。同时,我们还实现了删除已上传文件的功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值