文件上傳控件第二波


上次分享了一款文件上傳控件(網址:http://www.cnblogs.com/ushou/archive/2013/01/17/2865332.html),功能也比較多,但總覺得不夠完美,經過近幾天的發酵,醞釀,終於生產啦,吼吼~~~

這次的上傳控件加入新的元素,比如附件列表展示、排序拖動、批量更新等。

俗話說,獨樂樂不如眾樂樂,現將關鍵代碼分享。

一,首先在MVC中新建分部視圖。

<link href="@Url.Content("~/Content/Uploadify/uploadify.css")" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="@Url.Content("~/Content/Uploadify/swfobject.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Content/Uploadify/jquery.uploadify.v2.1.4.min.js")"></script>
<script src="@Url.Content("~/Content/zDialog/zDialog.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Content/zDialog/zDrag.js")" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#uploadify").uploadify({
            'uploader': '/Content/Uploadify/uploadify.swf',
            'script': '/Ashx/UploadHandler.ashx',
            'cancelImg': '/Content/Uploadify/cancel.png',
            'folder': '/UploadFile',
            'queueID': 'fileQueue',
            'multi': true,
            'auto': true,
            'fileExt': '*.jpg;*.gif;*.png',
            'fileDesc': 'Image Files (.JPG, .GIF, .PNG)',
            'queueID': 'custom-demo',
            'queueSizeLimit': 9999,
            'simUploadLimit': 9999,
            'buttonText': '選擇文件',
            'removeCompleted': true,
            'onSelectOnce': function (event, data) {
            },
            'onComplete': function (event, queueId, fileObj, response, data) {                   
                AddFiles(response.split('|')[1], response.split('|')[2]);

            },
            'onAllComplete': function (event, data) {
            }
        });
    });
</script>

二:創建兩個ashx文件,兩個足矣,本來還想壓縮到一個的,后來想想還是算了。

這兩個ashx,分別擁有以下功能。

  1,對數據庫中的附件增、刪、改、查。

      關鍵代碼如下: 

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            string action = RequestExtension.GetQueryString<String>("action", "");

            if (action == "")
                return;
            MethodInfo methodInfo = this.GetType().GetMethod(action);
            if (methodInfo != null)
            {
                context.Response.Clear();
                context.Response.Write(methodInfo.Invoke(this, null));
                context.Response.End();
            }
        }

  這里action是傳入函數名稱,然后通過反射調用執行。

     用法也是相當簡捷:

    如下示例:

   修改:

   

            $.post("/Ashx/Attachment.ashx?action=Modify", { fileID: fileID, fileName: fileName, fileDesc: fileDesc }, function (txt) {
                if (txt == "OK") {
                    diag.close();
                }
                else {
                    Dialog.alert(txt);
                }
            }, "text");

  刪除:

            //發送請求到服務器刪除文件
            var fileID = $(obj).parent().parent().attr("id");
            $.post("/Ashx/Attachment.ashx?action=DelFile", { fileID: fileID }, function (txt) {
                if (txt == "OK") {
                    Dialog.close();
                    var p = $(obj).parent().parent();
                    p.css('display', 'none');
                }
                else {
                    Dialog.alert(txt);
                }
            }, "text");

  其他如新建、獲取用法也如此,不再細述。

三:JS中操作生成元素、與數據庫交互。

    這里是新增附件、批量修改、刪除附件的關鍵代碼,中間還有頁面元素拖動的功能。

    function AddFilesUseTb(fileName, fileID, imgUrl) {
        var cloneTb = $('#tbTemplete').clone().attr('id', fileID);
        $('#uploadMsg').append(cloneTb.wrap('<div></div>').parent().html());
        $("#" + fileID).find("input:eq(0)").val(fileName);

        if (imgUrl != null) {
            $("#" + fileID).find("img:eq(0)").attr("src", imgUrl);
        }

        //文件上傳完成后啟用sortable
        $('.gbin1-list').sortable().bind('sortupdate', function () {
            
        });
                
        //文件上傳完成后,自動更新序列號
        var fileList = $('#uploadMsg').find("table");
        var fileCount = $('#uploadMsg').find("table").length;
        $.post("/Ashx/Attachment.ashx?action=Modify", { fileID: fileID, fileName: fileName, fileDesc: "", IsMove: "N", sequenceNum: fileCount }, function (txt) {
            if (txt != "OK") {
                Dialog.alert("保存名稱為:" + fileName + "的文件時出錯,請重試");
            }
        }, "text");
    }

    function EditAllFiles(obj) {
        var fileList = $('#uploadMsg').find("table");
        var fileCount = $('#uploadMsg').find("table").length;
        for (var i = 0; i < fileCount; i++) {
            var fileID = $(fileList[i]).parent().attr("id");
            var fileName = $(fileList[i]).find("input:eq(0)").val();
            var fileDesc = $(fileList[i]).find("textarea:eq(0)").val();
            var IsMove = $(fileList[i]).find('input:checkbox:checked').val();
            if (IsMove == "on") {
                IsMove = "Y";
            }
            else {
                IsMove = "N";
            }
            $.post("/Ashx/Attachment.ashx?action=Modify", { fileID: fileID, fileName: fileName, fileDesc: fileDesc, IsMove: IsMove, sequenceNum: i+1 }, function (txt) {
                if (txt != "OK") {
                    Dialog.alert("保存名稱為:" + fileName + "的文件時出錯,請重試");
                }
            }, "text");
        }

        $(obj).val("已保存");
    };

    function DelAllFiles(obj) {
        Dialog.confirm('警告:確定要刪除附件?', function () {
            var fileList = $('#uploadMsg').find("table").each(function () {
                var fileID = $(this).parent().attr("id");
                var fileName = $(this).find("input:eq(0)").val();
                $.post("/Ashx/Attachment.ashx?action=DelFile", { fileID: fileID }, function (txt) {
                    if (txt != "OK") {
                        Dialog.alert("刪除名稱為:" + fileName + "的文件時出錯,請重試");
                    }
                }, "text");
            });
        });
    }

    function DelFiles(obj) {
        Dialog.confirm('警告:確定要刪除附件?', function () {

            //發送請求到服務器刪除文件
            var tbSelect = $(obj).parent().parent().parent().parent().parent();
            var fileID = tbSelect.attr("id");
            $.post("/Ashx/Attachment.ashx?action=DelFile", { fileID: fileID }, function (txt) {
                if (txt == "OK") {
                    Dialog.close();
                    tbSelect.css('display', 'none');
                }
                else {
                    Dialog.alert(txt);
                }
            }, "text");
        });
    }

  

四:頁如引用分部視圖,只需一句話:@Html.Action("Index", "File")

    話說這MVC還真是牛掰,比asp.net簡捷多了。

五:分享一下使用Dapper的分頁代碼。

        public KeyValuePair<Pagination, IList<AttachmentModel>> AttachmentPagination(Pagination pagin, AttachmentModel condition)
        {
            using (SqlConnection conn = DapperFactory.CrateOpenConnection())
            {
                String executeQuery = @"WITH pagintable AS(
                                        SELECT ROW_NUMBER() OVER(ORDER BY CreateDate DESC )AS RowID, ID, FileID, TabName, TabID, FileName, FileDesc, FilePath, FileTypeID, FileSize, CreateDate, CreateMan, EditDate, EditMan, IsValid, NeedMoveToMoss, IsMoveToMoss, IsTemp,SequenceNum FROM Attachment
                                        WHERE 1= 1) 
                                        SELECT * FROM pagintable where RowID between ((@CurrentPageIndex - 1)  * @PageSize) + 1  and (@CurrentPageIndex  * @PageSize)";
                String executeCount = "SELECT COUNT(*) AS CountNum FROM Attachment WHERE 1= 1";
                var mixCondition = new
                {
                    CurrentPageIndex = pagin.CurrentPageIndex,
                    PageSize = pagin.PageSize
                };
                List<AttachmentModel> listScore = conn.Query<AttachmentModel>(executeQuery, mixCondition).ToList();
                pagin.TotalItemCount = conn.Query<Int32>(executeCount, mixCondition).SingleOrDefault<Int32>();
                KeyValuePair<Pagination, IList<AttachmentModel>> result =
                    new KeyValuePair<Pagination, IList<AttachmentModel>>(pagin, listScore);
                return result;
            }
        }

  這是使用CodeSmith自動生成的代碼,秒秒鍾搞定,並且相當靈活及高效。

上張圖:

          備注:這張圖的兩個附件順序是可以拖動變更的,呵呵。

老樣子,提供Demo網址,供用戶試用及扒源碼。

網址:http://www.kxwg.net/File/FileUpload

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM