打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Jquery Uploadify用户插件测试Demo(.NET版本)

Jquery Uploadify用户插件测试Demo(.NET版本)

最近项目要用上传控件,所以找啊找啊找到了以前用的Uploadify插件,但是网上现在很多都是PHP版本....所以特地弄了个.net版本...总体感觉这个插件还是挺不错的~用户体验和API都还是满给力的

文件下载地址 http://www.uploadify.com/download/ ,里面主要涉及的一些参数概念如下,给JS插件中给定的参数都是json格式类型,下面是一些常用key属性

uploader : uploadify.swf 文件的相对路径,该swf文件是一个带有文字BROWSE的按钮,点击后淡出打开文件对话框,默认值:uploadify.swf。   
script :   后台处理程序的相对路径 。默认值:uploadify.php  
checkScript :用来判断上传选择的文件在服务器是否存在的后台处理程序的相对路径  
fileDataName :设置一个名字,在服务器处理程序中根据该名字来取上传文件的数据。默认为Filedata  
method : 提交方式Post 或Get 默认为Post  
scriptAccess :flash脚本文件的访问模式,如果在本地测试设置为always,默认值:sameDomain 
folder :  上传文件存放的目录 。  
queueID : 文件队列的ID,该ID与存放文件队列的div的ID一致。  
queueSizeLimit : 当允许多文件生成时,设置选择文件的个数,默认值:999 。  
multi : 设置为true时可以上传多个文件。  
fileExt : 设置可以选择的文件的类型,格式如:'*.doc;*.pdf;*.rar' 。  
sizeLimit : 上传文件的大小限制 。  
simUploadLimit : 允许同时上传的个数 默认值:1 。  
buttonText : 浏览按钮的文本,默认值:BROWSE 。  
buttonImg : 浏览按钮的图片的路径 。  
hideButton : 设置为true则隐藏浏览按钮的图片 。  
rollover : 值为true和false,设置为true时当鼠标移到浏览按钮上时有反转效果。  
width : 设置浏览按钮的宽度 ,默认值:110。  
height : 设置浏览按钮的高度 ,默认值:30。  
wmode : 设置该项为transparent 可以使浏览按钮的flash背景文件透明,并且flash文件会被置为页面的最高层。 默认值:opaque 。  
cancelImg :选择文件到文件队列中后的每一个文件上的关闭按钮图标,如下图:
fileDesc : 这个属性值必须设置fileExt属性后才有效,用来设置选择文件对话框中的提示文本,如设置fileDesc为“请选择rar doc pdf文件”,打开文件选择框效果如下图:
auto : 设置为true当选择文件后就直接上传了,为false需要点击上传按钮才上传 。

常用的事件参数
onInit : 做一些初始化的工作。
onSelect :选择文件时触发,该函数有三个参数
event:事件对象。
queueID:文件的唯一标识,由6为随机字符组成。
fileObj:选择的文件对象,有name、size、creationDate、modificationDate、type 5个属性。
onSelectOnce :在单文件或多文件上传时,选择文件时触发。该函数有两个参数event,data,data对象有以下几个属性:
fileCount:选择文件的总数。
filesSelected:同时选择文件的个数,如果一次选择了3个文件该属性值为3。
filesReplaced:如果文件队列中已经存在A和B两个文件,再次选择文件时又选择了A和B,该属性值为2。
allBytesTotal:所有选择的文件的总大小。
onCancel : 当点击文件队列中文件的关闭按钮或点击取消上传时触发。该函数有event、queueId、fileObj、data四个参数,前三个参数同onSelect 中的三个参数,data对象有两个属性fileCount和allBytesTotal。
fileCount:取消一个文件后,文件队列中剩余文件的个数。
allBytesTotal:取消一个文件后,文件队列中剩余文件的大小。
onClearQueue :当调用函数fileUploadClearQueue时触发。有event和data两个参数,同onCancel 中的两个对应参数。
onQueueFull :当设置了queueSizeLimit并且选择的文件个数超出了queueSizeLimit的值时触发。该函数有两个参数event和queueSizeLimit。
onError :当上传过程中发生错误时触发。该函数有event、queueId、fileObj、errorObj四个参数,其中前三个参数同上,errorObj对象有type和info两个属性。
type:错误的类型,有三种'HTTP’, 'IO’, or 'Security’
info:错误的描述 
onOpen :点击上传时触发,如果auto设置为true则是选择文件时触发,如果有多个文件上传则遍历整个文件队列。该函数有event、queueId、fileObj三个参数,参数的解释同上。
onProgress :点击上传时触发,如果auto设置为true则是选择文件时触发,如果有多个文件上传则遍历整个文件队列,在onOpen之后触发。该函数有event、queueId、fileObj、data四个参数,前三个参数的解释同上。data对象有四个属性percentage、bytesLoaded、allBytesLoaded、speed:
percentage:当前完成的百分比
bytesLoaded:当前上传的大小
allBytesLoaded:文件队列中已经上传完的大小
speed:上传速率 kb/s
onComplete:文件上传完成后触发。该函数有四个参数event、queueId、fileObj、response、data五个参数,前三个参数同上。response为后台处理程序返回的值,在上面的例子中为1或0,data有两个属性fileCount和speed
fileCount:剩余没有上传完成的文件的个数。
speed:文件上传的平均速率 kb/s
备注:fileObj对象和上面讲到的有些不太一样,onComplete 的fileObj对象有个filePath属性可以取出上传文件的路径。
onAllComplete:文件队列中所有的文件上传完成后触发。该函数有event和data两个参数,data有四个属性,分别为:
filesUploaded :上传的所有文件个数。
errors :出现错误的个数。
allBytesLoaded :所有上传文件的总大小。
speed :平均上传速率 kb/s

还有详细的API可以参照 http://www.uploadify.com/documentation/

言归正传,为项目做准备写了个小Demo大致如下效果

 主要前台代码如下:

JqueryUploadDemo.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %><asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">    Jquery Uploadify Demo</asp:Content><asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">    <h2>        JqueryUploadDemo</h2>    <div id="davidFile">    </div>    <input type="file" name="uploadify" id="uploadify" />    <br />    <div id="uploadResultDiv">        <table id="uploadResultList" class="datatables wp100 mbottom10">        </table>    </div>    <div id="successDialog">    </div>    <div id="errorDialog">    </div>    <script language="javascript" type="text/javascript">        //封装成一个初始化当前页的js类对象        var InitPage = function () {            var page = this;            //初始化成功提示框            var InitSuccessDialog = function () {                $('#successDialog').dialog({                    autoOpen: false,                    modal: true,                    draggable: false,                    resizable: false,                    width: 300,                    heigth: 200,                    position: ['center', 'center']                });            }            //初始化成功提示框            var InitErrorDialog = function () {                $('#errorDialog').dialog({                    autoOpen: false,                    modal: true,                    draggable: false,                    resizable: false,                    width: 300,                    heigth: 200,                    position: ['center', 'center'],                    button: { "OK": function () {                        $(this).dialog("close");                    }                    }                });            }            //初始化上传控件            page.InitUploadify = function () {                $("#uploadify").uploadify({                    "uploader": "../Scripts/uploadify-v2.1.4/uploadify.swf",                    "buttonText": "Browse..",                    "fileSizeLimit": "4096",                    "script": "/Test/GetFile",                    "cancelImg": "../Scripts/uploadify-v2.1.4/cancel.png",                    "folder": "UploadFile",                    "queueID": "davidFile",                    "auto": true,                    "multi": true,                    "fileExt": "*.JPG;*.GIG;*.PNG",                    "fileDesc": "Web Image Files (.JPG, .GIF, .PNG)",                    "onComplete": function (event, queueId, fileObj, response, data) {                        /*文件上传完成后触发。该函数有四个参数event、queueId、fileObj、response、data五个参数,前三个参数同上。response为后台处理程序返回的值,                        在上面的例子中为1或0,data有两个属性fileCount和speed                        ?fileCount:剩余没有上传完成的文件的个数。                         ?speed:文件上传的平均速率 kb/s 注:fileObj对象和上面讲到的有些不太一样,onComplete 的fileObj对象有个filePath属性可以取出上传文件的路径。                        */                        var responseJsonObj = JSON.parse(response);                        if (responseJsonObj.IsSuccess == 1) {                        } else {                            page.ShowErrorMessage("上传失败" + responseJsonObj.ErrorMessage);                            return false;                        }                    },                    "onAllComplete": function (event, data) {                        if (data.errors == 0) {                            page.ShowSuccessMessage("你成功上传了" + data.filesUploaded + "个文件!", "/Test/JqueryUploadDemo");                        }                    }                })            }            //获取上传文件列表            page.GetUploadFileList = function () {                $.getJSON("/Test/GetUploadFileList", {}, function (result) {                    $("#uploadResultDiv").html("<table id='uploadResultList' class='datatables wp100 mbottom10'></table>");                    var userTable = $("#uploadResultList").dataTable({                        "sDom": 'rt<"bottom"pfil>',                        "bJQueryUI": true,                        "bAjaxDataGet": false,                        "bAutoWidth": false,                        "bPaginate": true,                        "bLengthChange": true,                        "aaSorting": [[2, "desc"]],                        "aoColumns": [                            { "sTitle": "序号", "sClass": "wp6 sort taleft", "asSorting": ["desc", "asc"] },                            { "sTitle": "文件名", "sClass": "taleft sort wp10", "asSorting": ["desc", "asc"] },                            { "sTitle": "最后上传时间", "sClass": "taleft sort wp10", "asSorting": ["desc", "asc"] },                            { "sTitle": "操作", "sClass": "taleft sort wp10", "asSorting": ["desc", "asc"] }                            ],                        "aaData": result.aaData,                        "bInfo": true,                        "bFilter": false,                        "sPaginationType": "full_numbers",                        "bLengthChange": true,                        "oLanguage": {                            "sUrl": "http://www.cnblogs.com/Scripts/zh-cn.txt"                        }                    })                })            }            //删除文件            page.DeleteFile = function (filename) {                if (confirm("确认删除当前文件?")) {                    $.getJSON("/Test/DeleteFile", { delName: filename }, function (result) {                        if (result.IsSuccess == 1) {                            page.ShowSuccessMessage("删除成功!", "/Test/JqueryUploadDemo");                        } else {                            page.initDialog.ShowErrorMessage("删除失败!" + result.ErrorMessage);                        }                    })                }            }            //显示成功提示框1秒钟后返回指定页面            page.ShowSuccessMessage = function (message, targetUrl) {                $("#successDialog").html(message);                $("#successDialog").dialog("open");                setTimeout(function () {                    if (targetUrl == undefined || targetUrl == "" || targetUrl == null) {                        window.location = targetUrl;                    } else {                        $("#successDialog").dialog("close");                        page.GetUploadFileList();                    }                }, 1000);            }            //显示错误提示框            page.ShowErrorMessage = function (message) {                $("#errorDialog").html(message);                $("#errorDialog").dialog("open");            }            //初始化所有内部的Dialog            page.Init = function () {                var successDialog = new InitSuccessDialog();                var errorDialog = new InitErrorDialog();                var uploadifyObj = new page.InitUploadify();                var uploadList = new page.GetUploadFileList();            }        }        //创建类对象        var initPage = new InitPage();        initPage.Init()     </script></asp:Content>

 后台主要代码如下:

TestController
        public ActionResult JqueryUploadDemo()        {            return View();        }        /// <summary>        /// 获取Uploadify上传的文件        /// </summary>        /// <returns></returns>        public JsonResult GetFile()        {            string message = string.Empty;            bool result = false;            string[] allowedUploadFormatArr = new string[] { ".jpg", ".png", ".ico", ".doc", ".xlsx", ".xls", ".docx", ".zip", "rar" };            try            {                HttpPostedFile file = RequestHelper.FileQuery("FileData");                if (file == null)                    return Json(new { IsSuccess = 0, ErrorMessage = "获取文件为空!" }, JsonRequestBehavior.AllowGet);                else                {                    if (allowedUploadFormatArr.Contains(Path.GetExtension(file.FileName.Trim()).ToLower()))                    {                        string uploadPath = Request.MapPath("~/UploadFile");                        if (!Directory.Exists(uploadPath))                        {                            Directory.CreateDirectory(uploadPath);                            file.SaveAs(string.Concat(uploadPath, "\\", file.FileName));                        }                        else                            file.SaveAs(string.Concat(uploadPath, "\\", file.FileName));                        result = true;                    }                }            }            catch (Exception ex)            {                result = false;                message = ex.Message;            }            return Json(new { IsSuccess = result ? 1 : 0, ErrorMessage = message }, JsonRequestBehavior.AllowGet);        }        /// <summary>        /// 获取上传文件列表        /// </summary>        /// <returns></returns>        public JsonResult GetUploadFileList()        {            string uploadPath = Server.MapPath("~/UploadFile");            IList<object> fileList = new List<object>();            int index = 1;            foreach (string file in Directory.GetFiles(uploadPath))            {                FileInfo currentFile = new FileInfo(file);                fileList.Add(new object[] {                     index,                    string.Format("<a href='../UploadFile/{0}'>{0}</a>", currentFile.Name),                    currentFile.LastWriteTime.ToStandardString(),                    string.Format("<a href='javascript:void(0)' onclick='initPage.DeleteFile(\"{0}\")'>Delete</a>", currentFile.Name)                });                index++;            }            return Json(new { aaData = fileList.ToArray(), iTotalDisplayRecords = fileList.Count }, JsonRequestBehavior.AllowGet);        }        /// <summary>        /// 删除上传文件        /// </summary>        /// <param name="delName"></param>        /// <returns></returns>        public JsonResult DeleteFile(string delName)        {            string message = string.Empty;            bool result = false;            try            {                string uploadPath = Server.MapPath("~/UploadFile");                foreach (string file in Directory.GetFiles(uploadPath))                {                    FileInfo currentFile = new FileInfo(file);                    if (currentFile.Name.Trim().ToLower() == delName.Trim().ToLower())                        currentFile.Delete();                }                result = true;            }            catch (Exception ex)            {                result = false;                message = ex.Message;            }            return Json(new { IsSuccess = result ? 1 : 0, ErrorMessage = message }, JsonRequestBehavior.AllowGet);        }

希望对有需要朋友有用处~欢迎有各种其他控件推荐~

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
JQuery上传插件Uploadify使用详解
【第657期】ES6中Arguments和Parameters用法解析
前端上传组件Plupload使用指南
Uploadify 3.2 参数属性、事件、方法函数详解
python 常见100个常用函数
SWFUpload v2 说明文档 非常棒的多文件上传。
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服