Asp.net下载服务器文件

本文介绍了一个简单的ASP.NET Web应用程序中实现文件下载的方法。通过点击按钮触发DownloadMethod方法,该方法接收文件路径作为参数,并设置HTTP响应头以允许客户端下载指定的文件。

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

合作开发的时候,遇到几个问题,其中一个就是下载服务器的文件。

WebForm1.aspx有个Button1控件。

WebForm1.aspx.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text.RegularExpressions;

namespace Teat02
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void Button1_Click(object sender, EventArgs e)
        {

            DownloadMethod("~/UpLoadFiles/Files/练习.doc");//在这个地方有  “练习.doc”这个文档
        }

        private void DownloadMethod(string downloadfilepath)
        {
            
            string path = Server.MapPath(downloadfilepath);

            Regex re = new Regex(@"\w*\.\w*");
            string st = re.Match(path).Value.ToString();
            
            string fileName = st; //客户端保存的文件名


            FileInfo fileInfo = new FileInfo(path);
            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
            Response.AddHeader("Content-Length", fileInfo.Length.ToString());
            Response.AddHeader("Content-Transfer-Encoding", "binary");
            Response.ContentType = "application/octet-stream";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            Response.WriteFile(fileInfo.FullName);
            Response.Flush();
            Response.End();
        }
    }
}
通过DownloadMethod这个方法,只要将文件的路径传进去,就可以下载文件。


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值