1

当用户单击 ASP.NET C# 页面上的下载按钮时,我想从 FTP 下载文件并在用户的 Web 浏览器中打开下载/保存提示。

string strDownloadURL = System.Configuration.ConfigurationSettings.AppSettings["DownloadURL"];
string HostName = System.Configuration.ConfigurationSettings.AppSettings["HostName"];
string strUser = System.Configuration.ConfigurationSettings.AppSettings["BasicAuthenticationUser"];
string strPWD = System.Configuration.ConfigurationSettings.AppSettings["BasicAuthenticationPWD"];

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(HostName + strFile);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(strUser, strPWD);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;

FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
string fileName = @"c:\temp\" + strFile + "";
Directory.CreateDirectory(Path.GetDirectoryName(fileName));
FileStream file = File.Create(fileName);
byte[] buffer = new byte[2 * 1024];
int read;
while ((read = responseStream.Read(buffer, 0, buffer.Length)) > 0) { file.Write(buffer, 0, read); }
file.Close();
responseStream.Close();
response.Close();
4

2 回答 2

0

因此,假设您正在将 FTP 请求的响应流写入 ASP.NET 响应流,并希望在浏览器中触发下载对话框,您需要Content-Disposition在响应中设置标头。

// note: since you are writing directly to client, I removed the `file` stream
// in your original code since we don't need to store the file locally...
// or so I am assuming
Response.AddHeader("content-disposition", "attachment;filename=" + strFile);

byte[] buffer = new byte[2 * 1024];
int read;
while ((read = responseStream.Read(buffer, 0, buffer.Length)) > 0) 
{ 
   Response.OutputStream.Write(buffer, 0, read);
}

responseStream.Close();
response.Close();
于 2012-06-15T09:23:57.407 回答
0

@moribvndvs 的答案是正确的。但是使用WebClient.OpenReadand可以使代码更简单Stream.CopyTo

var filename = "file.zip";
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);

var client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
var url = "ftp://ftp.example.com/remote/path/" + filename;
using (var ftpStream = client.OpenRead(url))
{
    ftpStream.CopyTo(Response.OutputStream);
}

ASP.NETResponse在哪里)。HttpResponse

另请参阅在 C#/.NET 中向/从 FTP 服务器上传和下载文件

于 2021-09-08T06:11:50.117 回答