[英]Download file ASP.NET C#
我正在嘗試將文件下載到計算機上的任何位置,但是當我單擊按鈕時,它會直接將其發送到我的下載文件夾中。 我正在使用的代碼如下:
我希望能夠選擇“桌面,我的文檔,ETC”。 我究竟做錯了什么?
protected void Button1_Click(object sender, EventArgs e)
{
// The file path to download.
string filepath = @"C:\Test\Test.docx";
// The filename used to save the file to the client's system..
string filename = Path.GetFileName( filepath );
Stream stream = null;
try
{
// Open the file into a stream.
stream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read );
// Total bytes to read:
long bytesToRead = stream.Length;
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename );
// Read the bytes from the stream in small portions.
while ( bytesToRead > 0 )
{
// Make sure the client is still connected.
if (Response.IsClientConnected)
{
// Read the data into the buffer and write into the
// output stream.
byte[] buffer = new Byte[10000];
int length = stream.Read(buffer, 0, 10000);
Response.OutputStream.Write(buffer, 0, length);
Response.Flush();
// We have already read some bytes.. need to read
// only the remaining.
bytesToRead = bytesToRead - length;
}
else
{
// Get out of the loop, if user is not connected anymore..
bytesToRead = -1;
}
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
// An error occurred..
}
finally
{
if ( stream != null ) {
stream.Close();
}
}
}
這與您的瀏覽器設置有關-您使用哪種瀏覽器? 無論如何,請轉到瀏覽器的設置,找到下載選項,然后告訴他們先問您將其保存在哪里。
對於谷歌瀏覽器: 更改下載位置
對於Firefox: 更改單擊或下載文件時Firefox的功能
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.