合作开发的时候,遇到几个问题,其中一个就是下载服务器的文件。
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这个方法,只要将文件的路径传进去,就可以下载文件。