[點(diǎn)晴永久免費(fèi)OA][ASP.NET]web實(shí)現(xiàn)用FTP上傳、下載文件(附源碼)
文章配套源碼下載地址:
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協(xié)議下載</th> <th>ftp協(xié)議下載</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" ) %>/<%#Eval("fileName") %>'>http://djk8888csdn.3vcm.net/<%#Eval("ftpURI") %>/<%#Eval("fileName") %></a></td> <td><input type="button" value="下載" οnclick=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> /// 這是一個(gè)完整的例子 /// </summary> public partial class index : System.Web.UI.Page { static string strfile = "info.txt";//txt文件名 string txtPath = HttpContext.Current.Server.MapPath(strfile);//相對路徑轉(zhuǎn)絕對路徑 string strout = string.Empty;//txt文件里讀出來的內(nèi)容 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內(nèi)容較少可用此法 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(';');//分解每一組數(shù)據(jù) 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('│');//分解每一個(gè)屬性 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();//文件擴(kuò)展名 //限制上傳文件最大不能超過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; } //創(chuàng)建文件夾 string ftpURI = DateTime.Now.ToString("yyyyMMdd");//以日期作為文件夾名稱 try { FtpWeb.CreateDirectory(ftpURI);//創(chuàng)建文件夾 } catch { } //準(zhǔn)備上傳文件 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,追加一行數(shù)據(jù) 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('請選擇一個(gè)文件再上傳!');</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協(xié)議下載文件 /// </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">報(bào)錯(cuò)信息</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);//創(chuàng)建FtpWebRequest實(shí)例uploadRequest uploadRequest.Method = WebRequestMethods.Ftp.UploadFile;//將FtpWebRequest屬性設(shè)置為上傳文件 uploadRequest.Credentials = new NetworkCredential(ftpUserID, ftpPassword);//認(rèn)證FTP用戶名密碼 requestStream = uploadRequest.GetRequestStream();//ftp上的空文件 int buffLength = 2048; //開辟2KB緩存區(qū) 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(); } } //創(chuàng)建文件夾 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">報(bào)錯(cuò)信息</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);//創(chuàng)建本地空文件 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(); } } } 文章配套源碼下載地址: 該文章在 2020/5/22 10:02:43 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |