用asp.net怎样实现文件下载!急的很啊,大家帮帮忙吧!在现等呀!
我要网页中实现文件的下载,但是我不会做。请问一下大家有没有能够直接运行的代码,因为我用了很多代码都运行不了,大家多多帮忙啊,多谢了! --------------------编程问答-------------------- 在页面上拖个datagridprivate void Page_Load(object sender, System.EventArgs e)
{
Excel();
// 在此处放置用户代码以初始化页面
}
private void Excel()
{
DataGrid1.DataSource =自己需要的数据源;
DataGrid1.DataBind ();
Response.ContentType ="application/vnd.ms-excel";
Response.Charset ="";
EnableViewState=false;
System.IO .StringWriter tw=new System.IO.StringWriter ();
System.Web .UI .HtmlTextWriter hw=new HtmlTextWriter (tw);
DataGrid1.RenderControl (hw);
Response.Write (tw.ToString ());
Response.End() ;
} --------------------编程问答-------------------- 楼上你那是导出excel不是文件下载。。。
private bool DownLoadFile(HttpRequest req, HttpResponse res, string fileName, string fullPath, long Speed)
{
try
{
FileStream fs = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader br = new BinaryReader(fs);
res.AddHeader("Accept-Ranges", "bytes");
long filelenght = fs.Length;
long startbytes = 0;
double pack = 10240;
int sleep = (int)Math.Floor(1000 * pack / Speed) + 1;
if (req.Headers["Range"] != null)
{
res.StatusCode = 206;
string[] range = req.Headers["Range"].Split(new char[] { '=', '-' });
startbytes = Convert.ToInt64(range[1]);
}
res.AddHeader("Content-Length", (filelenght - startbytes).ToString());
if (startbytes != 0)
{
//Response.AddHeader("Content-Range",string.Format("byte{0}-{1}/{2}",startbytes,filelenght-1,filelenght));
}
res.AddHeader("Connection", "Keep-Alive");
res.ContentType = "application/octet-stream";
res.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
br.BaseStream.Seek(startbytes, SeekOrigin.Begin);
int MaxCount = (int)Math.Floor((filelenght - startbytes) / pack) + 1;
for (int i = 0; i < MaxCount; i++)
{
if (res.IsClientConnected)
{
res.BinaryWrite(br.ReadBytes(int.Parse(pack.ToString())));
Thread.Sleep(sleep);
}
else
{
i = MaxCount;
}
}
br.Close();
fs.Close();
}
catch (Exception ex)
{
return false;
}
return true;
} --------------------编程问答-------------------- DownLoadFile(Page.Request, Page.Response, "filename", @_filePath, 102400); --------------------编程问答-------------------- 给楼主一个类。直接按参数传进去就可以实现的啦。
--------------------编程问答-------------------- 你要下载啥文件 超链接能满足你不
///<summary>
/// 输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小
/// </summary>
/// <param name="MyRequest">Page.Request对象</param>
/// <param name="MyResponse">Page.Response对象</param>
/// <param name="MyFileName">下载文件名</param>
/// <param name="MyFullPath">带文件名下载路径</param>
/// <param name="MySpeed">每秒允许下载的字节数</param>
/// <returns>True Or False</returns>
public bool ResponseFile(HttpRequest MyRequest, HttpResponse MyResponse, string MyFileName, string MyFullPath, long MySpeed)
{
try
{
FileStream myFile = new FileStream(MyFullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader br = new BinaryReader(myFile);
try
{
MyResponse.AddHeader("Accept-Ranges", "bytes");
MyResponse.Buffer = false;
long fileLength = myFile.Length;
long startBytes = 0;
int pack = 10240; //10K bytes
int sleep = (int)Math.Floor(1000.0 * pack / MySpeed) + 1;
if (MyRequest.Headers["Range"] != null)
{
MyResponse.StatusCode = 206;
string[] range = MyRequest.Headers["Range"].Split(new char[] { '=', '-' });
startBytes = Convert.ToInt64(range[1]);
}
MyResponse.AddHeader("Content-Length", (fileLength - startBytes).ToString());
if ((startBytes != 0))
{
MyResponse.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
}
MyResponse.AddHeader("Connection", "Keep-Alive");
MyResponse.ContentType = "application/octet-stream";
MyResponse.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(MyFileName, System.Text.Encoding.UTF8));
br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
int maxCount = (int)Math.Floor(1.0 * (fileLength - startBytes) / pack) + 1;
for (int i = 0; i <= maxCount; i++)
{
if ((MyResponse.IsClientConnected))
{
MyResponse.BinaryWrite(br.ReadBytes(pack));
System.Threading.Thread.Sleep(sleep);
}
else
{
i = maxCount;
}
}
}
catch
{
return false;
}
finally
{
br.Close(); myFile.Close();
}
}
catch
{
return false;
}
return true;
}
或者用文件流给客户端写文件 --------------------编程问答-------------------- 汗。。。
直接把文件的链接地址给出来不行么? --------------------编程问答-------------------- 我给你个短小精悍的,绝对好用,支持中文不乱码,一般人我不告诉他~~~~~~~
/// <summary>
/// 文件下载类
/// </summary>
/// <param name="FullFileName">服务器上的物理路径,可以用Server.Mappath获取</param>
private void FileDownload(string FullFileName)
{
FileInfo DownloadFile = new FileInfo(FullFileName);
Response.Clear();
Response.ClearHeaders();
Response.Buffer = false;
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(DownloadFile.FullName, System.Text.Encoding.UTF8));
Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
Response.WriteFile(DownloadFile.FullName);
Response.Flush();
Response.End();
}
//简单调用方法
string ID = Request.QueryString["ID"].ToString();
using (SqlConnection con = new SqlConnection(这里是连接字符串))
{
con.Open();
SqlCommand cmd = new SqlCommand("select FileName FROM LB_DownLoad where ID='"+ID+"'", con);
string fileName = Convert.ToString(cmd.ExecuteScalar());
FileDownload(Server.MapPath(fileName)); }
补充:.NET技术 , ASP.NET