把文件从服务器的文件夹中下载下来 弹出另存为的对话框

本文介绍了两种在ASP.NET中实现文件下载的方法:一种是使用传统的方法通过WriteFile进行下载,另一种是利用ASP.NET 2.0新增的TransmitFile方法,后者能更高效地处理大文件下载,避免了内存占用问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果直接引用文件的下载地址(url)会直接打开文件,并不会弹出另存为的对话框(对于已知MIME).

找到两种方法.(前面写过一篇,从数据库上传,下载的文章,正好和这个做个对应.)

第一种是最一般的.

        // Identify the file to download including its path.
        string filepath = Server.MapPath("softfile/this.rar");

        // Identify the file name.
        string filename = System.IO.Path.GetFileName(filepath);

        Response.Clear();

        // Specify the Type of the downloadable file.
        Response.ContentType = "application/octet-stream";

        // Set the Default file name in the FileDownload dialog box.
        Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);

        Response.Flush();

        // Download the file.
        Response.WriteFile(filepath);

第二种是,用了asp.net2.0版中,新提供的一个方法TransmitFile().

将指定的文件直接写入 HTTP 响应输出流,而不在内存中缓冲该文件。 
这么做的好处就是解决了writefile()的,输出时会占用服务器大量内存.效率低下,不能下载大文件的问题.

下面是一个小例子.
        string filepath = Server.MapPath("softfile/this.rar");
        string filename = System.IO.Path.GetFileName(filepath);                
        Response.Clear();
        Response.ContentType = "application/octet-stream";
        Response.AppendHeader ("Content-Disposition", "attachment;filename="+filename );
//这里的filename可以输出时自定义,不一定用原来的.
        Response.TransmitFile(filepath );
        Response.Flush();
        Response.Close();

 

 

来源:http://hi.baidu.com/beyoung/blog/item/ba2a6a604bde3844ebf8f898.html

转载于:https://www.cnblogs.com/hubj/archive/2008/09/16/1291980.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值