jquery.form + ASP.NET MVC 上传文件

 运行效果:

 

保存上传文件路径:

 

 

 

 jquery.form 下载地址http://jquery.malsup.com/form/#download  

 

HTML:

<link href="~/Content/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<style type="text/css">
    .mt-5 {
        margin-top: 5px;
    }

    .mb-5 {
        margin-bottom: 5px;
    }

    .ml-5 {
        margin-left: 5px;
    }

    .c-red {
        color: red;
    }
</style>

<!-- class="uploader" 必须的  -->
<!-- id:保存文件服务器位置 input 的 name -->
<div id="ImgLogo" class="uploader uploadImg" btnUploadVal="上传 Logo"></div>


<div id="ImgBanner" class="uploadImg" btnUploadVal="上传 Banner"></div>

<div id="downloadFile" class="uploader uploadFile" btnUploadVal="上传附件"></div>

<script src="~/scripts/jquery-1.10.2.min.js"></script>
<script src="~/scripts/jquery.form.min.js"></script>
<script src="~/scripts/uploadFiles.js"></script>
<script type="text/javascript">
    $(function () {
        //上传图片
        //初始化多个
        //$(".uploadImg").uploadImages({ thumbWidth: 150 });
        //初始化一个
        $("#ImgLogo").uploadImages({ thumbWidth: 150 });
        //默认参数
        //$(".uploadImg").uploadImages({
        //    url: "/Home/UploadImage",  //设置post提交到的页面
        //    uploadfileName: "file",   // 提交上传控件 name
        //    imgUrl: "/upload/noPic.jpg",   //默认图片地址
        //    thumbWidth: 100,  //缩略图宽度
        //    btnUploadVal: "上传图片",  //上传按钮显示文字
        //    btnDelVal: "删除", //删除按钮显示文字
        //    data: null,   //额外参数 { dirName: "images" }
        //    maxSize: 2 * 1024 * 1024,  // 上传大小限制,单位B,默认2MB
        //    allowFiles: [".png", ".jpg", ".jpeg", ".gif", ".bmp"]    //允许上传格式
        //});

        //上传文件
        $(".uploadFile").uploadFiles({ maxSize: 1*1024 * 1024 * 1024 });
        //默认参数
        //$(".uploadFile").uploadFiles({
        //    url: "/Home/UploadFile",  //设置post提交到的页面
        //    uploadfileName: "file",   // 提交上传控件 name
        //    btnUploadVal: "上传文件",  //上传按钮显示文字
        //    btnDelVal: "删除", //删除按钮显示文字
        //    data: null,   //额外参数 { dirName: "files" }
        //    maxSize: 50 * 1024 * 1024, //上传大小限制,单位B,默认50MB
        //    allowFiles: [
        //        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        //        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        //        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        //        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        //        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
        //    ]     //允许上传格式
        //});
    });
</script>

 

 uploadFiles.js

 

; (function () {
    //上传文件检测
    var checkFile = function (fileCtrl, maxSize, arrAllowFiles) {
        //是否有上传文件
        var file = fileCtrl.val();
        if (file == "") {
            return "上传文件出错:请选择要上传的文件";
        }

        //console.log(fileCtrl[0].files[0].size);
        //检测上传大小
        if (fileCtrl[0].files[0].size > maxSize) {
            return "上传文件出错:文件大小不能超过" + (maxSize / (1024 * 1024)) + "M";
        }

        var lastDotIndex = file.lastIndexOf(".");
        var type = file.toLowerCase().substring(lastDotIndex + 1);
        //console.log(arrAllowFiles);
        var extc = '.' + type;  //.jpg
        var allowFilesFlg = false;  //是否支持格式
        for (var i = 0; i < arrAllowFiles.length; i++) {
            //console.log(arrAllowFiles[i]);
            if (extc === arrAllowFiles[i]) {
                allowFilesFlg = true;
                break;
            }
        }
        if (!allowFilesFlg) {
            return "上传文件出错:不支持 " + extc + " 格式";
        }

        return "";
    };

    $.fn.extend({
        "uploadImages": function (options) {
            var defaults = {
                url: "/WebAdmin/Uploader/UploadImage",  //设置post提交到的页面
                uploadfileName: "file",   // 提交上传控件 name
                imgUrl: "/upload/noPic.jpg",   //默认图片地址
                thumbWidth: 100,  //缩略图宽度
                btnUploadVal: "上传图片",  //上传按钮显示文字
                btnDelVal: "删除", //删除按钮显示文字
                data: null,   //额外参数 { dirName: "images" } 
                maxSize: 2 * 1024 * 1024,  // 上传大小限制,单位B,默认2MB 
                allowFiles: [".png", ".jpg", ".jpeg", ".gif", ".bmp"]    //允许上传格式
            };

            //获取默认图片地址
            var defaultImgUrl = defaults.imgUrl;

            //设置默认值
            options = $.extend(defaults, options);

            //console.log(defaults.imgUrl);
            //console.log(options.imgUrl);

            var $uploadWrap = $(this);



            //初始化控件
            $uploadWrap.each(function (index) {
                var $this = $(this);

                //保存上传路径控件的 name
                var idName = $this.attr("id");

                //console.log(idName + "-" + $this.attr("class") + "-" + index);

                //是否显示默认缩略图
                if (options.imgUrl!=""&&defaultImgUrl != options.imgUrl) {
                    $this.append("<div class='thumb'><img src='" + options.imgUrl + "' width='" + options.thumbWidth + "'/></div>")
                } else {
                    $this.append("<div class='thumb'></div>")
                }

                //$this.append("<div class='thumb mb-5'><img src='" + options.imgUrl + "' width='" + options.thumbWidth + "'/></div>")
                $this.append("<div class='btnGroup mt-5'><button type='button' class='btn btn-secondary radius btnUpload'><i class='Hui-iconfont'>&#xe642;</i> " + options.btnUploadVal + "</button></div>")
                       .append("<input type='text' class='fileUrl' name='" + idName + "' value='" + options.imgUrl + "'  style='display:none;' />")
                       .append("<input type='file' class='upfile' style='display:none;' />")
                       .append("<div class='progress radius mt-5' style='display:none;'></div>")
                       .append("<div class='errorMsg c-red mt-5' style='display:none;'></div>");

                //设置初始值
                if (options.imgUrl != "" && defaultImgUrl != options.imgUrl) {
                    //添加删除按钮
                    if ($this.find(".btnDel").length <= 0) {
                        $this.find(".btnGroup").append("<button type='button' class='btn btn-danger radius btnDel ml-5'><i class='Hui-iconfont'>&#xe6e2;</i> " + options.btnDelVal + "</button>");
                    }
                }
                        
            });

            //绑定上传事件
            $uploadWrap.find(".btnUpload").on('click', function () {
                var $parent = $(this).parents(".uploader");
                $parent.find(".upfile").click();
            });

            //绑定删除按钮事件
            $uploadWrap.on('click', '.btnDel', function () {
                //获取父元素对象
                var $parent = $(this).parents(".uploader");

                //初始化图片地址
                $parent.find(".fileUrl").val("");
                //删除缩略图
                $parent.find(".thumb").html("");


                //移除删除按钮
                $(this).remove();
            });

            //上传文件
            $uploadWrap.find(".upfile").on('change', function () {

                //获取父元素对象
                var $parent = $(this).parents(".uploader");

                //检测上传文件
                var errorMsg = checkFile($(this), options.maxSize, options.allowFiles);
                //console.log(errorMsg);
                if (errorMsg!="") {
                    $parent.find(".errorMsg").text(errorMsg).show();
                    return false;
                }

                // console.log($parent.attr("id"));
                //构建新的表单提交数据(只提交文本域)
                var from = $("<form id='formUpload' enctype='multipart/form-data'></form>");

                from.append($(this).clone().attr("name", options.uploadfileName)); //获取文件选择控件添加到新表单
                //alert($(this).val());
                from.ajaxSubmit({
                    url: options.url, /*设置post提交到的页面*/
                    type: "post", /*设置表单以post方法提交*/
                    dataType: "json", /*设置返回值类型为文本*/
                    data: options.data, /* 传递额外参数 */
                    //上传进度
                    uploadProgress: function (event, position, total, percentComplete) {
                        //console.log(percentComplete, position, total);
                        $parent.find(".progress").show().html("<div class='progress-bar'><span class='sr-only' style='width:" + percentComplete + "%'></span></div>");
                    },

                    //提交后的回调函数
                    success: function (res) {
                        //初始化进度条
                        $parent.find(".progress").hide();

                        if (res.status == "ok") {

                            //显示图片
                            $parent.find(".thumb").html("<img src='" + res.data.path + "?t=" + new Date() + "' width='" + options.thumbWidth + "'/>");

                            //保存文件路径
                            $parent.find(".fileUrl").val(res.data.path);


                            //清空上传控件
                            $parent.find(".upfile").val('');

                            //添加删除按钮
                            if ($parent.find(".btnDel").length <= 0) {
                                $parent.find(".btnGroup").append("<button type='button' class='btn btn-danger radius btnDel ml-5'><i class='Hui-iconfont'>&#xe6e2;</i> " + options.btnDelVal + "</button>");
                            }

                            //删除错误提示
                            $parent.find(".errorMsg").text("").hide();
                        }
                        else if (res.status == "error") {
                            //清空上传控件
                            $parent.find(".upfile").val('');
                            //alert(res.ErrorMsg);
                            //错误提示
                            $parent.find(".errorMsg").text("上传文件出错:" + res.errorMsg).show();
                        }
                    },
                    error: function (error) {
                        //alert(error);
                        //错误提示
                        $parent.find(".errorMsg").text("上传文件出错:" + error).show();
                    }
                });
            });
        },
        "uploadFiles": function (options) {
            var defaults ={
                url: "/WebAdmin/Uploader/UploadFile",  //设置post提交到的页面
                uploadfileName: "file",   // 提交上传控件 name
                btnUploadVal: "上传文件",  //上传按钮显示文字
                btnDelVal: "删除", //删除按钮显示文字
                defaultUrl: "",    //默认地址
                data: null,   //额外参数 { dirName: "files" } 
                maxSize: 50 * 1024 * 1024, //上传大小限制,单位B,默认50MB 
                allowFiles: [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
                ]     //允许上传格式
            };

            //设置默认值
            options = $.extend(defaults, options);

            var $uploadWrap = $(this);


            //初始化控件
            $uploadWrap.each(function (index) {
                var $this = $(this);

                //保存上传路径控件的 name
                var idName = $this.attr("id");

                //console.log(idName + "-" + $this.attr("class") + "-" + index);

                $this.append("<input type='text' class='input-text mb-5 fileUrl' name='" + idName + "' value='" + options.defaultUrl + "' readonly='readonly' style='width:100%;' />")
                       .append("<div class='btnGroup'><button type='button' class='btn btn-secondary radius btnUpload'><i class='Hui-iconfont'>&#xe642;</i> " + options.btnUploadVal + "</button></div>")
                       .append("<input type='file' class='upfile' style='display:none;' />")
                       .append("<div class='progress radius mt-5' style='display:none;'></div>")
                       .append("<div class='errorMsg c-red mt-5' style='display:none;'></div>");

                //设置初始值
                if (options.defaultUrl) {
                    //添加删除按钮
                    if ($this.find(".btnDel").length <= 0) {
                        $this.find(".btnGroup").append("<button type='button' class='btn btn-danger radius btnDel ml-5'><i class='Hui-iconfont'>&#xe6e2;</i> " + options.btnDelVal + "</button>");
                    }
                }
            });

            //绑定上传事件
            $uploadWrap.find(".btnUpload").on('click', function () {
                $(this).parents(".uploader").find(".upfile").click();
            });

            //绑定删除按钮事件
            $uploadWrap.on('click', '.btnDel', function () {
                //获取父元素对象
                var $parent = $(this).parents(".uploader");

                //初始化图片地址
                $parent.find(".fileUrl").val("");

                //移除删除按钮
                $(this).remove();
            });

            //上传文件
            $uploadWrap.find(".upfile").on('change', function () {
                //获取父元素对象
                var $parent = $(this).parents(".uploader");


                //检测上传文件
                var errorMsg = checkFile($(this), options.maxSize, options.allowFiles);
                //console.log(errorMsg);
                if (errorMsg != "") {
                    $parent.find(".errorMsg").text(errorMsg).show();
                    return false;
                }

                // console.log($parent.attr("id"));
                //构建新的表单提交数据(只提交文本域)
                var from = $("<form id='formUpload' enctype='multipart/form-data'></form>");

                from.append($(this).clone().attr("name", options.uploadfileName)); //获取文件选择控件添加到新表单
                //alert($(this).val());
                from.ajaxSubmit({
                    url: options.url, /*设置post提交到的页面*/
                    type: "post", /*设置表单以post方法提交*/
                    dataType: "json", /*设置返回值类型为文本*/
                    data: options.data, /* 传递额外参数 */
                    //上传进度
                    uploadProgress: function (event, position, total, percentComplete) {
                        //console.log(percentComplete, position, total);
                        $parent.find(".progress").show().html("<div class='progress-bar'><span class='sr-only' style='width:" + percentComplete + "%'></span></div>");
                    },

                    //提交后的回调函数
                    success: function (res) {
                        //初始化进度条
                        $parent.find(".progress").hide();

                        if (res.status == "ok") {

                            //保存文件路径
                            $parent.find(".fileUrl").val(res.data.path);

                            //清空上传控件
                            $parent.find(".upfile").val('');

                            //添加删除按钮
                            if ($parent.find(".btnDel").length <= 0) {
                                $parent.find(".btnGroup").append("<button type='button' class='btn btn-danger radius btnDel ml-5'><i class='Hui-iconfont'>&#xe6e2;</i> " + options.btnDelVal + "</button>");
                            }

                            //删除错误提示
                            $parent.find(".errorMsg").text("").hide();
                        }
                        else if (res.status == "error") {
                            //清空上传控件
                            $parent.find(".upfile").val('');
                            //alert(res.ErrorMsg);
                            //错误提示
                            $parent.find(".errorMsg").text("上传文件出错:" + res.errorMsg).show();
                        }
                    },
                    error: function (error) {
                        //alert(error);
                        //错误提示
                        $parent.find(".errorMsg").text("上传文件出错:" + error).show();
                    }
                });
            });
        }
    });
})(jQuery);

 

 

 

 

服务端处理:

 

#region 上传文件
public ActionResult UploadImage(HttpPostedFileBase file, string dirName = "images")
{
    //限制上传大小
    int maxSize = 2 * 1024 * 1024;
    //允许上传文件
    string[] allowFiles = { ".png", ".jpg", ".jpeg", ".gif", ".bmp" };
    return Json(BaseUploadFile(file, dirName, maxSize, allowFiles));
}

public ActionResult UploadFile(HttpPostedFileBase file, string dirName = "files")
{
    //限制上传大小
    int maxSize = 1*1024 * 1024 * 1024;
    //允许上传文件
    string[] allowFiles = { ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"};
    return Json(BaseUploadFile(file, dirName, maxSize, allowFiles));
}

/// <summary>
/// 上传文件
/// </summary>
/// <param name="file">上传控件</param>
/// <param name="dirName">上传到哪个目录</param>
/// <param name="maxSize">限制上传大小</param>
/// <param name="allowFiles">允许上传文件格式</param>
/// <returns></returns>
public AjaxResult BaseUploadFile(HttpPostedFileBase file, string dirName, int maxSize, string[] allowFiles)
{
    if (file == null)
    {
        return new AjaxResult { Status = "error", ErrorMsg = "获取不到文件资源" };
    }

    if (file.ContentLength <= 0)
    {
        return new AjaxResult { Status = "error", ErrorMsg = "文件大小为0" };
    }

    //限制上传大小
    if (file.ContentLength > maxSize)
    {
        return new AjaxResult { Status = "error", ErrorMsg = "文件大小不能超过" + (maxSize / (1024 * 1024)) + "M" };
    }

    //获取文件后缀名
    string ext = Path.GetExtension(file.FileName);

    //允许上传文件
    bool allowFilesFlg = false;
    foreach (string allowFile in allowFiles)
    {
        if (ext == allowFile)
        {
            allowFilesFlg = true;
            break;
        }
    }
    if (!allowFilesFlg)
    {
        return new AjaxResult { Status = "error", ErrorMsg = "不支持" + ext + "格式" };
    }

    //month月,minute
    string md5 = CommonHelper.CalcMD5(file.InputStream);
    string path = "/upload/" + dirName + "/" + DateTime.Now.ToString("yyyy/MM/dd") + "/" + md5 + ext;// /upload/2017/07/07/afadsfa.jpg
    string fullPath = HttpContext.Server.MapPath("~" + path);//d://22/upload/2017/07/07/afadsfa.jpg
    new FileInfo(fullPath).Directory.Create();//尝试创建可能不存在的文件夹

    file.InputStream.Position = 0;//指针复位
    file.SaveAs(fullPath); //SaveAs("d:/1.jpg");

    return new AjaxResult { Status = "ok", Data = new { path = path } };
}
#endregion


public class AjaxResult
{
    /// <summary>
    /// 执行的结果
    /// </summary>
    public string Status { get; set; }

    /// <summary>
    /// 错误消息
    /// </summary>
    public string ErrorMsg { get; set; }

    /// <summary>
    /// 执行返回的数据
    /// </summary>
    public object Data { get; set; }
}

 

限制文件上传大小参考:

.net mvc 超过了最大请求长度 限制文件上传大小

 

参考资料:

jQuery插件定义

 

posted @ 2018-09-02 23:55  linyongqin  阅读(845)  评论(0编辑  收藏  举报