[ASP.NET]web实现用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协议下载</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();
        }
    }
}
文章配套源码下载地址:https://download.csdn.net/download/djk8888/10486581


winform的ftp上传下载:https://blog.csdn.net/djk8888/article/details/80662238

猜你喜欢

转载自blog.csdn.net/djk8888/article/details/80736524