首页 > 代码库 > 在浏览器中从FTP下载文件

在浏览器中从FTP下载文件

 1     public static class FTPHelper 2     { 3         /// <summary> 4         /// 得到特定FTP目录的文件列表 5         /// </summary> 6         /// <param name="uri">ftp://{username}:{password}@ftp.baidu.com/{folderName}</param> 7         public static List<String> ListFiles(Uri serverUri) 8         { 9             // The serverUri parameter should start with the ftp:// scheme.10             if (serverUri.Scheme != Uri.UriSchemeFtp)11             {12                 throw new ArgumentException("uri must be ftp scheme");13             }14 15             FtpWebRequest ftpRequest = null;16             StreamReader reader = null;17             try18             {19                 // Get the object used to communicate with the server.20                 ftpRequest = (FtpWebRequest)FtpWebRequest.Create(serverUri);21 22                 ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;23 24                 reader = new StreamReader(ftpRequest.GetResponse().GetResponseStream(), Encoding.Default);25 26                 //read data.27                 List<String> fileNames = new List<String>();28                 string line = reader.ReadLine();29                 while (line != null)30                 {31 32                     fileNames.Add(line);33                     line = reader.ReadLine();34                 }35 36                 return fileNames;37 38             }39             catch(Exception ex)40             {41                 throw ex;42             }43             finally44             { 45               if(reader != null)46               {47                   reader.Close();48               }49               if (ftpRequest != null)50               {51                   ftpRequest.Abort();52               }53             }54         }55 56         /// <summary>57         /// 得到特定文件的大小58         /// </summary>59         /// <param name="uri">ftp://{username}:{password}@ftp.baidu.com/{fileName}</param>60         public static long GetFileSize(Uri serverUri)61         {62             // The serverUri parameter should start with the ftp:// scheme.63             if (serverUri.Scheme != Uri.UriSchemeFtp)64             {65                 throw new ArgumentException("uri must be ftp scheme");66             }67 68             FtpWebRequest ftpRequest = null;69             StreamReader reader = null;70             try71             {72                 // Get the object used to communicate with the server.73                 ftpRequest = (FtpWebRequest)FtpWebRequest.Create(serverUri);74 75                 ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize;76 77                 return ftpRequest.GetResponse().ContentLength;78             }79             catch (Exception ex)80             {81                 throw ex;82             }83             finally84             {85                 if (reader != null)86                 {87                     reader.Close();88                 }89                 if (ftpRequest != null)90                 {91                     ftpRequest.Abort();92                 }93             }94         }95     }

调用ListFile方法把FTP特定目录的所有文件列表显示在web页面上,当单击名称时,下载文件

        /// <summary>        /// 下载文件(此方法定义在实现Controller某类的某个MVC Controller中)        /// </summary>        /// <param name="uri"></param>        public void DownLoadFile(Uri uri,string fileName)        {            //Create a stream for the file            Stream stream = null;            //This controls how many bytes to read at a time and send to the client            int bytesToRead = 10000;            // Buffer to read bytes in chunk size specified above            byte[] buffer = new Byte[bytesToRead];            // The number of bytes read            try            {                long fileSize = FTPHelper.GetFileSize(uri);                //Create a WebRequest to get the file                FtpWebRequest fileReq = (FtpWebRequest)FtpWebRequest.Create(uri);                //Create a response for this request                FtpWebResponse fileResp = (FtpWebResponse)fileReq.GetResponse();                //Get the Stream returned from the response                stream = fileResp.GetResponseStream();                // prepare the response to the client. resp is the client Response                var resp = HttpContext.Response;                //Indicate the type of data being sent                resp.ContentType = "application/octet-stream";                //Name the file                 resp.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");                resp.AddHeader("Content-Length", fileSize.ToString());                int length;                do                {                    // Verify that the client is connected.                    if (resp.IsClientConnected)                    {                        // Read data into the buffer.                        length = stream.Read(buffer, 0, bytesToRead);                        // and write it out to the response‘s output stream                        resp.OutputStream.Write(buffer, 0, length);                        // Flush the data                        resp.Flush();                        //Clear the buffer                        buffer = new Byte[bytesToRead];                    }                    else                    {                        // cancel the download if client has disconnected                        length = -1;                    }                } while (length > 0); //Repeat until no data is read            }            finally            {                if (stream != null)                {                    //Close the input stream                    stream.Close();                }            }        }

 

在浏览器中从FTP下载文件