C# 之 FTP服务器中文件上传与下载(三)

33 篇文章 10 订阅

通过上一篇博客《C# 之 FTP服务器中文件上传与下载(二)》,我们已经实现将文件上传到我们创建的FTP服务器。今天我们就一起来看看怎么样实现从FTP服务器中下载我们所需要的文件。


        我们想实现的效果是在页面上有一个超链接,超链接显示为我们想要下载的文件名。点击该文件名进入下载页面。首先我们在前台插入一个超链接,但是这个超链接为后台拼接的超链接。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


public partial class _Default : System.Web.UI.Page
{
    public static string strFileContent = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        string strPath = "ftp://192.168.1.100:21/1.png";    //文件在ftp服务器中存放路径
        string strFileName = "1.png";   //文件名


        //拼接超链接
        strFileContent = "<a class=\"ke-insertfile\" href=\"/DownLoad.aspx?strPath=" + strPath + "&strFileName=" + strFileName + "\" target=\"_blank\">" + strFileName + "</a>";
    }
}


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:FileUpload ID="fuImage" runat="server" Width="400px" />
    <asp:Button runat="server" ID="btnUpLoad" Text="上传" CssClass="nButton" OnClick="btnUpLoad_Click" />
    </div>
    <div>
    <%= strFileContent %>   <%--需要下载的文件名--%>
    </div>
    </form>
</body>
</html>



然后,我们新加入一个下载页面,此页面前台不需要任何东西

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DownLoad.aspx.cs" Inherits="DownLoad" %>

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>--%>

编写最重要的后台下载代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class DownLoad : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        UpDownLoad();
    }

    /// <summary>
    /// 下载附件
    /// </summary>
    public void UpDownLoad()
    {

        string strPath = Request["strPath"].ToString(); //该文件在ftp服务器中的存放路径
        string strFileName = Request["strFileName"].ToString(); //文件名
        string strUserName = "hehe";    //ftp登录用户名
        string strPassword = "123456";  //ftp登录密码

        System.Net.WebClient request = new System.Net.WebClient();
        request.Credentials = new System.Net.NetworkCredential(strUserName, strPassword);//认证FTP用户名密码  
        byte[] newFileData = request.DownloadData(strPath);

        //下载文件
        DownLoadFile(strFileName, newFileData, this.Page);


    }

    public static void DownLoadFile(string FileName, byte[] Context, Page page)
    {
        page.Response.ContentType = "application/octet-stream";
        if (FileName == "")
        {
            FileName = "Temp";
        }
        FileName = ToHexString(FileName);
        page.Response.AddHeader("Content-Disposition", "attachment;FileName=" + FileName);
        if (Context != null && Context.Length > 0)
            page.Response.OutputStream.Write(Context, 0, Context.Length);
        else
            page.Response.BinaryWrite(new byte[1]);
        page.Response.End();
    }


    public static string ToHexString(string s)
    {
        char[] chars = s.ToCharArray();
        StringBuilder builder = new StringBuilder();
        for (int index = 0; index < chars.Length; index++)
        {
            bool needToEncode = NeedToEncode(chars[index]);
            if (needToEncode)
            {
                string encodedString = ToHexString(chars[index]);
                builder.Append(encodedString);
            }
            else
            {
                builder.Append(chars[index]);
            }
        }

        return builder.ToString();
    }

    private static bool NeedToEncode(char chr)
    {
        string reservedChars = "$-_.+!*'(),@=&";

        if (chr > 127)
            return true;
        if (char.IsLetterOrDigit(chr) || reservedChars.IndexOf(chr) >= 0)
            return false;

        return true;
    }

    private static string ToHexString(char chr)
    {
        UTF8Encoding utf8 = new UTF8Encoding();
        byte[] encodedBytes = utf8.GetBytes(chr.ToString());
        StringBuilder builder = new StringBuilder();
        for (int index = 0; index < encodedBytes.Length; index++)
        {
            builder.AppendFormat("%{0}", Convert.ToString(encodedBytes[index], 16));
        }
        return builder.ToString();
    }
}

下面看看咱们的效果



点击超链接,下载文件


选择存放路径,点击下载



这样我们就将我们存放在ftp服务器中的文件下载到我们本地




  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值