[转载]文件上传控件第二波 - tebato - 博客园

[转载]文件上传控件第二波 – tebato – 博客园.

上次分享了一款文件上传控件(网址: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网址,供用户试用及扒源码。

网址:www.qicheba.net

赞(0) 打赏
分享到: 更多 (0)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏