从MVC中的FTP下载文件

时间:2018-11-19 08:36:10

标签: asp.net-mvc

我们已经在FTP文件夹上上传了文件,现在我要在AJax的下载文件夹中下载此文件

我已经从FTP下载了文件,但是单击URL后无法下载

这是我的代码

public ActionResult DownloadFile(ID){
string FileName = 'ABC.PDF'
string FTPFilePath = 'fTP pATH';

string ResponseDescription = "";
string PureFileName = new FileInfo(FileName).Name;
string DownloadedFilePath = strdirPath + "" + PureFileName;
string downloadUrl = FTPFilePath;

FtpWebRequest req = (FtpWebRequest)FtpWebRequest.Create(downloadUrl);
req.Credentials = new NetworkCredential(strFTPUserName, strFTPPassword);
req.Method = WebRequestMethods.Ftp.DownloadFile;
req.UseBinary = true;
req.Proxy = null;

FtpWebResponse response = (FtpWebResponse)req.GetResponse();
Stream stream = response.GetResponseStream();
FileStream fs = new FileStream(DownloadedFilePath, FileMode.Create);
byte[] buffer = new byte[2048];

int ReadCount = stream.Read(buffer, 0, buffer.Length);
while (ReadCount > 0)
{
    fs.Write(buffer, 0, ReadCount);
    ReadCount = stream.Read(buffer, 0, buffer.Length);
}

fs.Close();
stream.Close();
req = null;
response = null;

FileStream fs1 = new FileStream(strdirPath + PureFileName, FileMode.Open);
byte[] buffer1 = new byte[fs1.Length];
fs1.Read(buffer1, 0, Convert.ToInt32(fs1.Length));
fs1.Close();
System.IO.File.Delete(strdirPath + "" + PureFileName);

HttpContext.Response.Buffer = true;
HttpContext.Response.Expires = 0;
HttpContext.Response.ContentType = "plain/text";
HttpContext.Response.AddHeader("Content-Type", "plain/text");
HttpContext.Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Response.BinaryWrite(buffer1);
HttpContext.Response.End();

返回Json(“”,JsonRequestBehavior.AllowGet);}

0 个答案:

没有答案