[ASP.NET]web實現用FTP上傳、下載檔案(附原始碼)
阿新 • • 發佈:2019-02-08
index.aspx 頁:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="index" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>ASP.NET的FTP上傳和下載</title> <script src="http://code.jquery.com/jquery-latest.js"></script> </head> <body> <form id="form1" runat="server"> <div> <asp:FileUpload runat="server" ID="FileUpload"></asp:FileUpload> <asp:Button ID="Button1" runat="server" Text="FTP上傳" OnClick="Button1_Click" /> <asp:Button ID="Button2" runat="server" Text="重新整理列表" OnClick="Button2_Click" /> <br /> <br /> <table border="1" width="1000"> <tr> <th>編號</th> <th>資料夾</th> <th>檔名</th> <th>日期</th> <th>http協議下載</th> <th>ftp協議下載</th> </tr> <asp:Repeater runat="server" ID="Repeater1"> <ItemTemplate> <tr> <td><%#Eval("fileNo") %></td> <td><%#Eval("ftpURI") %></td> <td><%#Eval("fileName") %></td> <td><%#Eval("datetime") %></td> <td><a target="_blank" href='http://djk8888csdn.3vcm.net/<%#Eval("ftpURI") %>/<%#Eval("fileName") %>'>http://djk8888csdn.3vcm.net/<%#Eval("ftpURI") %>/<%#Eval("fileName") %></a></td> <td><input type="button" value="下載" onclick=ftpDownload('<%#Eval("ftpURI") %>','<%#Eval("fileName") %>') /></td> </tr> </ItemTemplate> </asp:Repeater> </table> </div> </form> </body> </html> <script type="text/javascript"> function ftpDownload(uri, name) { $.get("ftpDownload.ashx", { ftpURI: uri, fileName: name }, function (e) { if (e == "ok") { alert("下載成功!檔案在:\r\n C:\\" + name); } else { alert("下載失敗:\r\n" + e); } }); } </script>
index.aspx.cs 頁:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.UI.WebControls; /// <summary> /// 這是一個完整的例子 /// </summary> public partial class index : System.Web.UI.Page { static string strfile = "info.txt";//txt檔名 string txtPath = HttpContext.Current.Server.MapPath(strfile);//相對路徑轉絕對路徑 string strout = string.Empty;//txt檔案裡讀出來的內容 protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Bind(); } } //重新整理列表 protected void Button2_Click(object sender, EventArgs e) { Bind(); } private void Bind() { //string txt = File.ReadAllText(txtPath, Encoding.Default);//如果txt內容較少可用此法 if (File.Exists(txtPath)) { using (StreamReader sr = new StreamReader(System.Web.HttpContext.Current.Server.MapPath(strfile), System.Text.Encoding.Default)) { strout = sr.ReadToEnd(); string temp = strout.Replace("\r\n", ""); string[] strArr = temp.Split(';');//分解每一組資料 if (strArr != null && strArr.Any()) { int fileNo = 1; List<Info> list = new List<Info>(); foreach (var item in strArr) { if (!string.IsNullOrEmpty(item) && !string.IsNullOrWhiteSpace(item)) { string[] strArr2 = item.Split('|');//分解每一個屬性 Info info = new Info(); info.fileNo = fileNo; fileNo++; info.ftpURI = strArr2[0].ToString(); info.fileName = strArr2[1].ToString(); info.datetime = DateTime.Parse(strArr2[2].ToString()); list.Add(info); } } if (list != null && list.Any()) { this.Repeater1.DataSource = list.OrderByDescending(a => a.datetime); this.Repeater1.DataBind(); } } } } } protected void Button1_Click(object sender, EventArgs e) { string errorMsg = ""; if (FileUpload.HasFile) { int fileLength = FileUpload.PostedFile.ContentLength;//檔案大小,單位byte string fileName = Path.GetFileName(FileUpload.PostedFile.FileName);//檔名稱 string extension = Path.GetExtension(FileUpload.PostedFile.FileName).ToLower();//副檔名 //限制上傳檔案最大不能超過500M if (!(fileLength < 512 * 1024 * 1024)) { Response.Write("<script>alert('檔案最大不能超過500M!');</script>"); return; } //限制檔案格式 if (!".doc.docx.xls.xlsx.pdf.txt.jpg.jpeg".Contains(extension)) { Response.Write("<script>alert('不支援的檔案格式!');</script>"); return; } //建立資料夾 string ftpURI = DateTime.Now.ToString("yyyyMMdd");//以日期作為資料夾名稱 try { FtpWeb.CreateDirectory(ftpURI);//建立資料夾 } catch { } //準備上傳檔案 Stream fileStream = null; try { fileStream = FileUpload.PostedFile.InputStream;//讀取本地檔案流 var b = FtpWeb.Upload(ftpURI, fileName, fileLength, fileStream, out errorMsg);//開始上傳 if (b) { if (File.Exists(txtPath)) { FileStream myStream = new FileStream(txtPath, FileMode.Append, FileAccess.Write);// FileMode.Append,追加一行資料 StreamWriter sw = new StreamWriter(myStream); sw.WriteLine(ftpURI + "|" + fileName + "|" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ";");//寫入檔案 sw.Close(); } Bind(); Response.Write("<script>alert('上傳成功!');</script>"); } else { Response.Write("<script>alert('上傳失敗!" + errorMsg + "');</script>"); } } catch (Exception ex) { Response.Write("<script>alert('上傳失敗!" + ex.ToString() + "');</script>"); } finally { if (fileStream != null) fileStream.Close(); } } else { Response.Write("<script>alert('請選擇一個檔案再上傳!');</script>"); } } public class Info { public int fileNo { get; set; } public string ftpURI { get; set; } public string fileName { get; set; } public DateTime datetime { get; set; } } }
ftpDownload.ashx 頁:
<%@ WebHandler Language="C#" Class="ftpDownload" %> using System; using System.Web; public class ftpDownload : IHttpHandler { /// <summary> /// ftp協議下載檔案 /// </summary> /// <param name="context"></param> public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string ftpURI = context.Request.QueryString["ftpURI"];//ftpURI string fileName = context.Request.QueryString["fileName"];//fileName string localPath = "C:\\";//檔案下載路徑(可自定義) string errorMsg = ""; bool b = FtpWeb.Download(ftpURI, localPath, fileName, out errorMsg); if (b) { context.Response.Write("ok"); } else { context.Response.Write(errorMsg); } } public bool IsReusable { get { return false; } } }
FtpWeb.cs 頁:
using System;
using System.IO;
using System.Net;
/// <summary>
/// web地址: http://djk8888csdn.3vcm.net/
/// FTP地址: ftp://013.3vftp.com/
/// FTP賬號: djk8888csdn
/// FTP密碼: 123456
/// </summary>
public class FtpWeb
{
public static string ftpHost = "ftp://013.3vftp.com/";//FTP的ip地址或域名
public static string ftpUserID = "djk8888csdn";//ftp賬號
public static string ftpPassword = "123456";//ftp密碼
/// <summary>
/// 上傳
/// </summary>
/// <param name="ftpURI">ftp上的路徑</param>
/// <param name="filename">ftp上的檔名</param>
/// <param name="fileLength">檔案大小</param>
/// <param name="localStream">本地檔案流</param>
/// <param name="errorMsg">報錯資訊</param>
/// <returns></returns>
public static bool Upload(string ftpURI, string filename, int fileLength, Stream localStream, out string errorMsg)
{
errorMsg = "";
Stream fileStream = null;//本地檔案流
Stream requestStream = null;//ftp檔案流
try
{
fileStream = localStream;//本地檔案流
Uri uri = new Uri(ftpHost + ftpURI + "/" + filename);//ftp完整路徑
FtpWebRequest uploadRequest = (FtpWebRequest)WebRequest.Create(uri);//建立FtpWebRequest例項uploadRequest
uploadRequest.Method = WebRequestMethods.Ftp.UploadFile;//將FtpWebRequest屬性設定為上傳檔案
uploadRequest.Credentials = new NetworkCredential(ftpUserID, ftpPassword);//認證FTP使用者名稱密碼
requestStream = uploadRequest.GetRequestStream();//ftp上的空檔案
int buffLength = 2048; //開闢2KB快取區
byte[] buff = new byte[buffLength];
int contentLen;
contentLen = fileStream.Read(buff, 0, buffLength);
while (contentLen != 0)
{
requestStream.Write(buff, 0, contentLen);//將本地檔案流寫入到ftp上的空檔案中去
contentLen = fileStream.Read(buff, 0, buffLength);
}
requestStream.Close();
fileStream.Close();
return true;
}
catch (Exception ex)
{
errorMsg = ex.Message;
return false;
}
finally
{
if (fileStream != null) fileStream.Close();
if (requestStream != null) requestStream.Close();
}
}
//建立資料夾
public static string CreateDirectory(string ftpDir)
{
FtpWebRequest request = SetFtpConfig(WebRequestMethods.Ftp.MakeDirectory, ftpDir);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
return response.StatusDescription;
}
private static FtpWebRequest SetFtpConfig(string method, string ftpDir)
{
return SetFtpConfig(method, ftpDir, "");
}
private static FtpWebRequest SetFtpConfig(string method, string ftpDir, string fileName)
{
ftpDir = string.IsNullOrEmpty(ftpDir) ? "" : ftpDir.Trim();
return SetFtpConfig(ftpHost, ftpUserID, ftpPassword, method, ftpDir, fileName);
}
private static FtpWebRequest SetFtpConfig(string host, string username, string password, string method, string RemoteDir, string RemoteFileName)
{
System.Net.ServicePointManager.DefaultConnectionLimit = 50;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(host + RemoteDir + "/" + RemoteFileName);
request.Method = method;
request.Credentials = new NetworkCredential(username, password);
request.UsePassive = false;
request.UseBinary = true;
request.KeepAlive = false;
return request;
}
/// <summary>
/// FTP檔案下載(程式碼僅供參考)
/// </summary>
/// <param name="ftpURI">fpt檔案路徑</param>
/// <param name="localPath">本地檔案路徑</param>
/// <param name="fileName">ftp檔名</param>
/// <param name="errorMsg">報錯資訊</param>
/// <returns></returns>
public static bool Download(string ftpURI, string localPath, string fileName, out string errorMsg)
{
errorMsg = "";
FtpWebRequest reqFTP = null;
FileStream outputStream = null;
Stream ftpStream = null;
FtpWebResponse response = null;
try
{
outputStream = new FileStream(localPath + "/" + fileName, FileMode.Create);//建立本地空檔案
Uri uri = new Uri(ftpHost + ftpURI + "/" + fileName);//ftp完整路徑
reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);//登入ftp
response = (FtpWebResponse)reqFTP.GetResponse();
ftpStream = response.GetResponseStream();//讀取ftp上檔案流
long cl = response.ContentLength;
int bufferSize = 2048;//緩衝
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);//將ftp檔案流寫入到本地空檔案中去
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
return true;
}
catch (Exception ex)
{
errorMsg = ex.Message;
return false;
}
finally
{
if (ftpStream != null) ftpStream.Close();
if (outputStream != null) outputStream.Close();
if (response != null) response.Close();
}
}
}