通過 標簽實現ftp文件下載功能


環境:

ftp登錄用戶名

ftp登錄密碼

ftp文件路徑

一般處理程序

下面是我通過網上查找的資料實現的一個例子

首先頁面中的a 標簽拼接路徑帶需要的參數

<a class="downST" href="../ashx/Folder.ashx?strPath=ftp://[ftp ip地址]/PLM/File/標准ztree數據.txt&FileName=標准ztree數據.txt">下載</a>

下面是處理程序代碼

 public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        string strUserName = "****";    //ftp登錄用戶名
        string strPassword = "******.";  //ftp登錄密碼

            string FileName = context.Request["FileName"].ToString();
             string address = context.Request["strPath"].ToString();

        System.Net.WebClient request = new System.Net.WebClient();
        request.Credentials = new System.Net.NetworkCredential(strUserName, strPassword);//認證FTP用戶名密碼  
        byte[] newFileData = request.DownloadData(address );

        ////下載文件
        //DownLoadFile(strFileName, newFileData, HttpContext context1);
        
         context.Response.ContentType = "application/octet-stream";
        if (FileName == "")
        {
            FileName = "Temp";
        }
        FileName = ToHexString(FileName);
        context.Response.AddHeader("Content-Disposition", "attachment;FileName=" + FileName);
        if (newFileData != null && newFileData.Length > 0)
            context.Response.OutputStream.Write(newFileData, 0, newFileData.Length);
        else
            context.Response.BinaryWrite(new byte[1]);
        context.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();
    }
    public bool IsReusable {
        get {
            return false;
        }
    }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM