ASP.NET表单和一般处理程序处理文件上传和下载

来源:互联网 发布:sql 合计函数 编辑:程序博客网 时间:2024/05/16 07:16

1.文件上传。分为服务端和浏览器两部分

    public void ProcessRequest(HttpContext context)    {        context.Response.ContentType = "text/html";        // 判断是否有文件上来。即直接访问上传页时的判断        if (context.Request.Files.Count <= 0)        {            context.Response.Write("无上传。");            context.Response.End();// 结束输出        }        // 测试。取第一个文件来做。        HttpPostedFile hpf = context.Request.Files[0];        // 判断是否有文件。由浏览器发送一个post请求过来,看是否有上传控件传送的数据        if (hpf.ContentLength <= 0)        {            context.Response.Write("无上传文件。");            context.Response.End();        }        // 判断文件类型。        if (hpf.ContentType != "image/jpeg" && hpf.ContentType != "image/pjpeg" && hpf.ContentType != "image/jpg")        {            context.Response.Write("文件类型不符。");            context.Response.End();        }        // 获取文件在客户端的物理位置或文件名加后缀        string filename = hpf.FileName;        string ext = System.IO.Path.GetExtension(filename);        // 为文件取新名字。        Random r = new Random();        string name = DateTime.Now.ToString("yyyyMMddhhmmss") + r.Next(100, 1000) + ext;        // 服务器上的位置        string url = context.Request.MapPath("upload") + "/" + name;        // 将浏览器传递的数据保存到服务器上。        hpf.SaveAs(url);        context.Response.Write("上传成功。");    }
html部分。也需要写js代码判断是否存在文件和文件类型

    <form action="文件上传.ashx" method="post" enctype="multipart/form-data">        <input name="file" type="file" />        <input type="submit" />    </form>

2.文件下载。

    public void ProcessRequest(HttpContext context)    {        // 获取传递来的文件名,并对其转码        string name = context.Request.QueryString["url"];        string enname = HttpUtility.UrlEncode(name);        // 注意此时是在服务端读写文件,不能对文件名进行转码。        string path = context.Request.MapPath("files/" + name);        // 在http头上注明,这是附件,文件名是什么。        context.Response.AddHeader("Content-Disposition", "attachment;filename=" + enname);        // 输出文件。        context.Response.WriteFile(path);    }