【www.gdgbn.com--组件控件开发】

asp教程.net 利用服务器控件上传和下载文件

第一步,选择上传文件。每二步,判断文件格式。第三步,指定存放目录,第四步,保存文件。

 

废话不多说直接上菜:

   

 

       

 

        <script type="text/网页特效">

            function fun_checktype() {

            var filename = document.getelementbyid("fileupload").value;

 

            if (filename == "") {

                alert("请选择上传的文件!");

                return false;

            }

 

            var seat = filename.lastindexof(".");

            var extension = filename.substring(seat).tolowercase();

            //设定格式

            var allowed = [".jpg", ".gif", ".png", ".bmp", ".jpeg", ".sql", ".txt", ".doc", ".xls"];

 

            for (var i = 0; i < allowed.length; i++) {

                if (!(allowed[i] != extension)) {

                     return true;

                 }

             }

 

            alert("不支持" + extension + "格式!");

            return false;

            }

        </script>

 

源码很干净简单,就不多做解释,需要注意一点的是按钮的客户端点击事件:onclientclick

 

好了,凉菜已经上桌了,现在开始上主菜。 

 

protected void btnupload_click(object sender, eventargs e)

    {

        //指定文件存放目录,这里有个条件服务器中

        if (!system.io.directory.exists(server.mappath("~/filelist/files")))

            system.io.directory.createdirectory(server.mappath("~/filelist/files"));

 

        //保存文件

        fileupload.postedfile.saveas(server.mappath("~/filelist/files/" + fileupload.filename));

        scriptmanager.registerstartups教程cript(this.page, this.gettype(), "", "alert("上传成功");", true);

    }

 


当然在上传事件中会有一些逻辑判断和异常捕获,为了达到一目了然的效果,在这里就把它们省掉了。

 

补充一句删除文件代码:

//删除服务器上的文件

system.io.file.delete(server.mappath("~/filelist/files/xxx.doc"));

 

本文来源:http://www.gdgbn.com/asp/28700/