MVC文件图片ajax上传轻量级解决方案,使用客户端JSAjaxFileUploader插件02-多文件上传
            时间:2014-05-02 13:11:17  
            收藏:0  
            阅读:611
        
        
        上一篇中,使用客户端jJSAjaxFileUploader插件实现单文件异步上传,本篇实现多文件异步上传。
本篇源码在github,先看效果:
● 上传文件显示进度条。 
● 停止上传按钮和关闭缩略图按钮。      
● 限制上传文件的类型。      
● 限制上传文件的尺寸。      
●同时上传多个文件成功后显示缩略图、文件名:
● 点击界面上的删除按钮,界面删除,同步删除文件夹中文件。     
● 
再点击上传文件,界面追加一行新的缩略图、文件名、删除按钮:
□ HomeController
把上传的文件名改成以GUID命名的格式,避免多文件名称重复,并保存到文件夹,再把回传信息以json形式传递给视图。关于删除,需要接收来自视图的文件名参数。
        #region 上传多个文件        public ActionResult ShowMultiple()        {            return View();}
[HttpPost]
        public ActionResult UplpadMultipleFiles()        {            List<UploadFileResult> results = new List<UploadFileResult>();foreach (string file in Request.Files)
            {                HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;if (hpf.ContentLength == 0 || hpf == null)
                {                    continue;}
                //var fileName = DateTime.Now.ToString("yyyyMMddhhmmss") +                //               hpf.FileName.Substring(hpf.FileName.LastIndexOf(‘.‘));var fileName = Guid.NewGuid().ToString() +
                               hpf.FileName.Substring(hpf.FileName.LastIndexOf(‘.‘));string pathForSaving = Server.MapPath("~/AjaxUpload");
if (this.CreateFolderIfNeeded(pathForSaving))
                {hpf.SaveAs(Path.Combine(pathForSaving, fileName));
                    results.Add(new UploadFileResult()                    {                        FilePath = Url.Content(String.Format("~/AjaxUpload/{0}", fileName)),FileName = fileName,
                        IsValid = true,Length = hpf.ContentLength,
                        Message = "上传成功",Type = hpf.ContentType
});
}
}
return Json(new
            {name = results[0].FileName,
type = results[0].Type,
size = string.Format("{0} bytes", results[0].Length),
path = results[0].FilePath,
msg = results[0].Message
});
}
        #endregion        #region 共用方法        /// <summary>        /// 检查是否要创建上传文件夹,如果没有就创建        /// </summary>        /// <param name="path">路径</param>        /// <returns></returns>private bool CreateFolderIfNeeded(string path)
        {bool result = true;
            if (!Directory.Exists(path))            {                try                {Directory.CreateDirectory(path);
}
                catch (Exception)                {                    //TODO:处理异常                    result = false;}
}
            return result;}
        //根据文件名称删除文件[HttpPost]
public ActionResult DeleteFileByName(string name)
        {string pathForSaving = Server.MapPath("~/AjaxUpload");
System.IO.File.Delete(Path.Combine(pathForSaving, name));
return Json(new
            {                msg = true});
}
        #endregion
□ Home/ ShowMultiple.cshml
前台视图主要做如下几件事: 
● 上传成功动态创建表格行显示缩略图、文件名和删除按钮    
● 
点击删除按钮实施界面删除并同步删除文件夹中的文件   
由于表格行是动态生成的,需要对删除按钮以"冒泡"的方式注册事件: 
$(‘#tb‘).on("click", ".delImg", function ()
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="~/Content/JSAjaxFileUploader/JQuery.JSAjaxFileUploader.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-1.10.2.js"></script>    <script src="~/Scripts/JSAjaxFileUploader/JQuery.JSAjaxFileUploaderMultiple.js"></script>    <style type="text/css">        #tb table{border-collapse: collapse;
width: 600px;
}
        #tb td {text-align: center;
padding-top: 5px;
width: 25%;
}
        #tb tr {background-color: #E3E3E3;
line-height: 35px;
}
        .showImg {width: 50px;
height: 50px;
}
</style>
    <script type="text/javascript">        $(function () {            //隐藏显示图片的表格            $(‘#tbl‘).hide();            $(‘#testId‘).JSAjaxFileUploader({                uploadUrl: ‘@Url.Action("UplpadMultipleFiles","Home")‘,                inputText: ‘选择多个上传文件‘,                fileName: ‘photo‘,                maxFileSize: 512000,    //Max 500 KB file 1kb=1024字节                allowExt: ‘gif|jpg|jpeg|png‘,                zoomPreview: false,zoomWidth: 360,
zoomHeight: 360,
                success: function (data) {                    $(‘#tbl‘).show();createTableTr(data.path, data.name);
},
                error: function (data) {                    alert("出错了~~");}
});
            //点击行上的删除链接$(‘#tb‘).on("click", ".delImg", function () {
                var $link = $(this);                $.ajax({                    cache: false,                    url: ‘@Url.Action("DeleteFileByName", "Home")‘,                    type: "POST",                    data: { name: $link.parent().prev().find(‘.imgName‘).text() },                    success: function (data) {                        if (data.msg) {                            //alert("图片删除成功");$link.parent().parent().remove();
}
},
                    error: function (jqXhr, textStatus, errorThrown) {alert("出错了 ‘" + jqXhr.status + "‘ (状态: ‘" + textStatus + "‘, 错误为: ‘" + errorThrown + "‘)");
}
});
});
});
        //创建表格        function createTableTr(img, imgName) {            var table = $(‘#tbl‘);table.append("<tr><td><img class=‘showImg‘ src=‘" + img + "‘/></td><td colspan=‘2‘><span class=‘imgName‘>" + imgName + "</span></td><td><a class=‘delImg‘ href=‘javascript:void(0)‘>删除</a></td></tr>");
}
</script>
</head>
<body>
    <div id="testId"></div>    <div id="tb">        <table id="tbl"><tbody>
</tbody>
</table>
</div>
</body>
</html>
另外: 
需要把源js文件中input元素的multiple属性恢复,使之能接收多个文件。  
MVC文件图片ajax上传轻量级解决方案,使用客户端JSAjaxFileUploader插件02-多文件上传,布布扣,bubuko.com
            评论(0)
        
        
        
        
