当前位置: 移动技术网 > IT编程>开发语言>.net > asp.net(c#)开发中的文件上传组件uploadify的使用方法(带进度条)

asp.net(c#)开发中的文件上传组件uploadify的使用方法(带进度条)

2017年12月12日  | 移动技术网IT编程  | 我要评论

高梦潞,dnf2.1,3u8733

在web开发中,有很多可以上传的组件模块,利用html的file控件的上传也是一种办法,不过这种方式,需要处理的细节比较多,而且只能支持单文件的操作。在目前web开发中用的比较多的,可能uploadify(参考http://www.uploadify.com/)也算一个吧,不过这个版本一直在变化,他们的脚本调用也有很大的不同,甚至调用及参数都一直在变化,很早的时候,那个flash的按钮文字还没法变化,本篇随笔主要根据项目实际,介绍一下3.1版本的uploadify的控件使用,这版本目前还是最新的,因此对我们做web开发来说,有一定的参考性。

这个控件有很多参数控制,以及事件的处理响应,相对来说也比较好用。参数控制可以控制上传文件多选、文件类型、文件大小、文件数量、检查文件是否存在,以及一些按钮参数的控制,如文字、高度、宽度等,对提交文件成功与否、完成操作、取消、停止上传等等都有控制,他们的帮助文档也写得比较完善,不过就是各个版本的方法参数完全不同了,但控件是一个好控件。

控件的使用首先要加入必备的脚本类库,由于该控件是利用了jquery的功能,因此还需要应用jquery脚本文件,如下所示。

复制代码 代码如下:

    <script src="//www.jb51.net/jquery/jquery-1.8.0.min.js" type="text/javascript"></script>
    <script src="//www.jb51.net/jquerytools/uploadify/jquery.uploadify-3.1.min.js" type="text/javascript"></script>
    <link href="//www.jb51.net/jquerytools/uploadify/uploadify.css" rel="stylesheet" type="text/css" />

配置控件的一些参数,以及相应的处理事件,如下所示。

复制代码 代码如下:

<script language="javascript" type="text/javascript">
        $(function () {
            var guid = '<%=request["guid"] %>';
            var type = '<%=request["type"] %>';
            if (guid == null || guid == "") {
                guid = newguid();
            }
            if (type != null) {
                type = type + '/';
            }

            $('#file_upload').uploadify({
                'swf': 'uploadify.swf',                        //flash文件路径
                'buttontext': '浏  览',                        //按钮文本
                'uploader': 'uploadhandler.ashx?guid=' + guid, //处理ashx页面
                'formdata' : { 'folder' : 'picture' },         //传参数
                'queueid': 'filequeue',                        //队列的id
                'queuesizelimit': 10,                           //队列最多可上传文件数量,默认为999
                'auto': false,                                 //选择文件后是否自动上传,默认为true
                'multi': true,                                 //是否为多选,默认为true
                'removecompleted': true,                       //是否完成后移除序列,默认为true
                'filesizelimit': '10mb',                       //单个文件大小,0为无限制,可接受kb,mb,gb等单位的字符串值
                'filetypedesc': 'image files',                 //文件描述
                'filetypeexts': '*.gif; *.jpg; *.png; *.bmp',  //上传的文件后缀过滤器
                'onqueuecomplete': function (event, data) {    //所有队列完成后事件
                    //showupfiles(guid, type, show_div);
                    alert("上传完毕!");
                },
                'onuploaderror': function (event, queueid, fileobj, errorobj) {
                    alert(errorobj.type + ":" + errorobj.info);
                }
            });
        });

        function newguid() {
            var guid = "";
            for (var i = 1; i <= 32; i++){
              var n = math.floor(math.random()*16.0).tostring(16);
              guid +=   n;
              if((i==8)||(i==12)||(i==16)||(i==20))
                guid += "-";
            }
            return guid;
        }
    </script>

再次提一下,这个控件不要参考网上其他的一些说明,否则可能参数及用法不正确,一定要找到对应版本的说明(本篇指的是3.1.1),最好参考该版本的在线文档。

上面的参数,我基本上都给了注释了,还有一些不是很重要的参数,这里没有列出来,需要可以参考在线文档吧。

值得提到的是,这个版本可以修改flash里面的文字,非常棒,很讨厌以前的那个默认browse的英文,虽然以前替代图片可以修改文字,但是还是不太好用。这个直接修改文字,非常好。

值得注意的是uploader参数,这个是我们ashx的后台处理程序,就是控件提交文件给那个页面进行保存处理,添加数据库记录等操作。




页面代码使用很简单,如下所示

复制代码 代码如下:

<body style="margin-left:10px; margin-top:10px">
    <form id="form1" runat="server"  enctype="multipart/form-data">
    <div id="filequeue" class="filequeue"></div>

    <div>
    <input type="file" name="file_upload" id="file_upload" />
        <p>
            <input type="button" class="shortbutton" id="btnupload" onclick="javascript:$('#file_upload').uploadify('upload','*')" value="上传" />
                
            <input type="button" class="shortbutton" id="btncancelupload" onclick="javascript:$('#file_upload').uploadify('cancel')" value="取消" />
        </p>
        <div id="div_show_files"></div>
    </div>
    </form>
</body>


关键是后台上传文件的保存操作了,asp.net一般采用ashx的处理页面来处理。
复制代码 代码如下:

/// <summary>
    /// 文件上传后台处理页面
    /// </summary>
    [webservice(namespace = "http://tempuri.org/")]
    [webservicebinding(conformsto = wsiprofiles.basicprofile1_1)]
    public class uploadhandler : ihttphandler
    {
        public void processrequest(httpcontext context)
        {
            context.response.contenttype = "text/plain";
            context.response.charset = "utf-8";

            try
            {
                string guid = context.request.querystring["guid"];
                string folder = context.request["folder"];
                //logtexthelper.info(folder);

                httppostedfile file = context.request.files["filedata"];
                if (file != null)
                {                   
                    string oldfilename = file.filename;//原文件名                   
                    int size = file.contentlength;//附件大小

                    string extenstion = oldfilename.substring(oldfilename.lastindexof(".") + 1);//后缀名                   
                    string newfilename = getnewfilename(oldfilename);//生成新文件名
                    //logtexthelper.info(newfilename);

                    #region 上传到远程服务器
                    //fileservermanage fsw = new fileservermanage();
                    //string uploadfilepath = "/" + newfilename;
                    //if (!string.isnullorempty(folder))
                    //{
                    //    uploadfilepath = string.format("/{0}/{1}", folder, newfilename);
                    //}
                    //bool uploaded = fsw.uploadfile(file.inputstream, "/" + folder + "/" + newfilename);
                    #endregion

                    #region 本地服务器上传

                    appconfig config = new appconfig();
                    string uploadfiles = config.appconfigget("uploadfiles");
                    if (string.isnullorempty(uploadfiles))
                    {
                        uploadfiles = "uploadfiles";
                    }
                    if (!string.isnullorempty(folder))
                    {
                        uploadfiles = path.combine(uploadfiles, folder);
                    }

                    string uploadpath = path.combine(httpcontext.current.server.mappath("/"), uploadfiles);
                    if (!directory.exists(uploadpath))
                    {
                        directory.createdirectory(uploadpath);
                    }
                    string newfilepath = path.combine(uploadpath, newfilename);
                    logtexthelper.info(newfilepath);
                    file.saveas(newfilepath);
                    bool uploaded = file.exists(newfilepath);

                    #endregion

                    if (uploaded)
                    {
                        #region 文件保存成功后,写入附件的数据库记录
                        //attachmentinfo attachmentinfo = new attachmentinfo();
                        //attachmentinfo.editortime = datetime.now;
                        //attachmentinfo.fileextend = extenstion;
                        //attachmentinfo.filename = folader + "/" + newfilename;
                        //attachmentinfo.oldfilename = oldfilename;
                        //attachmentinfo.size = size;
                        //attachmentinfo.guid = guid;
                        //bllfactory<attachment>.instance.insert(attachmentinfo);
                        #endregion
                    }
                }
                else
                {
                    logtexthelper.error("上传文件失败");
                }
            }
            catch (exception ex)
            {
                logtexthelper.error("上传文件失败", ex);
                throw;
            }
        }

        /// <summary>
        /// 获取新的名称 比如:aa.jpg转化为aa(20090504).jpg
        /// </summary>
        /// <param name="filename">文件名称[aa.jpg]</param>
        /// <returns>新的文件名称</returns>
        public static string getnewfilename(string filename)
        {
            if (string.isnullorempty(filename))
                return string.empty;

            //文件后缀名
            string extenstion = filename.substring(filename.lastindexof(".") + 1);
            string name = filename.substring(0, filename.lastindexof(".")) + "(" + datetime.now.tofiletime() + ")";
            string newfilename = name + "." + extenstion;
            return newfilename;
        }

        public bool isreusable
        {
            get
            {
                return false;
            }
        }
    }



如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网