ASP.NET C#中的间接下载链接

时间:2012-09-12 21:00:56

标签: c# asp.net download

我想给用户,链接到我在服务器上的文件,但我不想让他们直接链接 使用asp.net C#

例如:

http://www.DomainName.com/Files/Downloads/setup.zip

转换为

http://www.DomainName.com/Files/?filename=setup

1 个答案:

答案 0 :(得分:5)

创建一个页面,例如DownloadMgr.aspx,它从查询字符串中读取文件名并将其写入响应流。

类似的东西:

protected void Page_Load(object sender, EventArgs e)
{
      string[] allowedExtensions = new string[] {".pdf",".zip",".txt", ".png"};
      if (!this.Page.IsPostBack)
      {
          if (Request.QueryString["File"] != null)
          {
             if (Request.QueryString["File"].Contains("pdf"))
                 Response.ContentType = "application/pdf"; //varies depending on the file being streamed
              Response.AddHeader("Content-Disposition", "attachment; filename=" + Request.QueryString["File"]);
              if(allowedFiles.Contains(Path.GetExtension(Request.QueryString["File"])))
                  Response.WriteFile(Server.MapPath(Request.QueryString["File"]));
           }
      }
}

现在您的所有链接都可以是:http://youhost.com/DownloadMgr.aspx?File=abc.pdf