[英]FIle Downloading asp.net
我正在嘗試使用asp.net上的按鈕下載文件,但是在我的情況下,按鈕為我提供了webform aspx
作為下載文件DownloadFileTest.apsx
。 我需要下載正確的文件。 這可能有助於我在解決方案資源管理器中上傳的文件也不會顯示。 但是如果我在項目文件夾中訪問它,它就會顯示出來。 這是代碼
protected void Button1_Click(object sender, EventArgs e)
{
string filename = TextBox1.Text;
Response.ContentType = "application/octet-stream";
Response.AppendHeader("content-diposition", "attach;filename" + filename);
Response.TransmitFile(Server.MapPath("~/CustomerFiles/" + filename));
Response.End();
}
您可以嘗試以下ASP.NET/C#代碼段:
internal static void Download(string FileName)
{
HttpResponse _response = HttpContext.Current.Response;
FileStream _fileStream;
byte[] _arrContentBytes;
try
{
// clear response obj
_response.Clear();
// clear content of response obj
_response.ClearContent();
// clear response headers
_response.ClearHeaders();
// enable response buffer
_response.Buffer = true;
// specify response content
_response.ContentType = ContentType;
_response.StatusCode = 206;
_response.StatusDescription = "Partial Content";
// create FileStream: IMPORTANT - specify FileAccess.Read
_fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
// Bytes array size= (int)_fs.Length;
_arrContentBytes = new byte[(int)_fileStream.Length];
// read file into bytes array
_fileStream.Read(_arrContentBytes, 0, (int)_fileStream.Length);
// add response header
_response.AddHeader("content-disposition", "attachment;filename=" + FileName);
// ACTUAL PROCEDURE: use BinaryWrite to download file
_response.BinaryWrite(_arrContentBytes);
// ALTERNATIVE: TransmitFile
//_response.TransmitFile(filePath);
// close FileStream
_fileStream.Flush();
_fileStream.Close();
_response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch { }
finally
{
_fileStream = null;
_arrContentBytes = null;
}
}
為了獲得根文件夾和完整路徑,您可以像在原始解決方案中那樣使用Server.MapPath
或以下行來獲得更好的性能:
// get the root dir; fast
string _root = AppDomain.CurrentDomain.BaseDirectory;
此解決方案已經在實際的Web應用程序( http://taxiom.com/Manual_Payday.aspx )中進行了測試/實現-請參閱演示頁面右上角的“下載”按鈕。 希望這會有所幫助。
這是我用來下載文件的代碼,請確保fuldFilNavn
包含文件的完整路徑:
public static void DownloadFil(string fuldFilNavn) { HttpContext context = HttpContext.Current; context.Response.ClearHeaders(); context.Response.ClearContent(); string filNavn = Uri.EscapeDataString(Path.GetFileName(fuldFilNavn)).Replace("+", "%20"); context.Response.AppendHeader("Content-Disposition", "attachment;filename*=utf-8''" + filNavn); context.Response.AppendHeader("Last-Modified", File.GetLastWriteTimeUtc(fuldFilNavn).ToString("R")); context.Response.ContentType = "application/octet-stream"; context.Response.AppendHeader("Content-Length", new FileInfo(fuldFilNavn).Length.ToString()); context.Response.TransmitFile(fuldFilNavn); context.Response.End(); }
這將下載文件名中帶有Unicode字符的文件!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.