http檔案上傳到web伺服器,上傳到ftp伺服器

來源:互聯網
上載者:User

前期準備:

   ftp:伺服器的配置。(為ftp上傳使用)。

   注意:

    1.要是你測試用,ftp就在你自己開發的機器上配置,一定別忘了要先建立使用者。且該使用者一定要有可讀寫的許可權!要不然會出現ftp 530錯誤!

    2.配置iis的ftp的時候一定把ftp的響應資訊寫成英文的,要不然會出現“基礎串連已經關閉: 伺服器提交了協議衝突。”錯誤。

    3.配置iis的ftp的時候最好不要使用匿名登陸!要不也會出現530錯誤!

開始:

  (一) web.config檔案的配置

         

<?xml version="1.0" encoding="utf-8"?>

<configuration>
    <connectionStrings/>
    <system.web>
        <compilation debug="false" />
        <authentication mode="Windows" />
        <httpRuntime maxRequestLength = "1048576"/><!--這個一定要寫上,要不然上傳的檔案大於1M的時候就可能出錯!預設支援是4M的,不過不穩定-->
    </system.web>
  <appSettings>
    <add key="download" value="/downLoad/aa.txt"/>
    <add key="upload" value="/upLoad/"/>
  </appSettings>
</configuration>

(二)aspx檔案

 

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>無標題頁</title>
</head>
<body style="text-align:center;">
    <form id="form1" runat="server" method="post">
    <div style="border:1px dotted red;width:400px;height:200px;text-align:left;">
        請選擇要上傳的檔案:
        <asp:FileUpload ID="filePathName" runat="server" />
        <br/><br/>
        <asp:Button ID="Button1" runat="server" Text="檔案上傳到ftp伺服器" OnClick="Button1_Click" />
        <asp:Button ID="Button3" runat="server" Text="檔案上傳到web伺服器" OnClick="Button3_Click" /></div>
    <br/>
    <div style="border:1px dotted red;width:400px;height:200px;text-align:left;">
        下載伺服器的資源檔:  <br/>
        <asp:Button ID="Button2" runat="server" Text="檔案下載" OnClick="Button2_Click" /></div>
    </form>
</body>
</html>

  (三).cs檔案

 

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Net;

public partial class _Default : System.Web.UI.Page
{
    private string downFile = null;
    private string upLoadPath = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        // 擷取配置的路徑
        downFile = Server.MapPath(".") + ConfigurationManager.AppSettings.Get("download");
        upLoadPath = Server.MapPath(".") + ConfigurationManager.AppSettings.Get("upload");
    }

    #region【檔案上傳】
    // ftp檔案上傳
    // fs:要上傳的檔案流,size:上傳檔案的大小,type:上傳檔案類型,fileNewname:要在伺服器上儲存的名稱
    private void FileFtpUpload(string fileNewname, string type, long size, Stream fs)
    {
        string strFileName = "";
        // 合成後的檔案名稱
        strFileName = fileNewname + DateTime.Now.Millisecond + "." + type;
        // 根據uri建立FtpWebRequest對象
        FtpWebRequest reqFTP;
        reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://192.168.100.81/" + strFileName));

        // ftp使用者名稱和密碼
        reqFTP.Credentials = new NetworkCredential("yans", "123456");

        // 銷毀到伺服器的串連
        reqFTP.KeepAlive = true;
        // 擷取或設定要發送到 FTP 伺服器的命令。
        reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
        // 傳輸檔案的資料格式Binary
        reqFTP.UseBinary = true;
        // 檔案是多大
        reqFTP.ContentLength = size;

        // 緩衝大小設定為2kb
        int buffLength = 2048;
        byte[] buff = new byte[buffLength];
        int contentLen;

        try
        {
            Stream strm = reqFTP.GetRequestStream();

            // 把檔案讀入到流中
            // FileStream fs = fileInf.OpenRead();
            // 用於儲存要由當前請求發送到伺服器的資料。
            // 把檔案流分裝成小的位元組數組,防止佔用太多的伺服器記憶體
            contentLen = fs.Read(buff, 0, buffLength);
            // 迴圈把檔案流寫入待發給ftp伺服器的請求流中
            while (contentLen != 0)
            {
                strm.Write(buff, 0, contentLen);
                contentLen = fs.Read(buff, 0, buffLength);
            }

            fs.Close();
            strm.Close();
        }
        catch (Exception e)
        {
            Response.Write(e.Message.ToString());
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (filePathName.FileName != "")
        {
             // 擷取檔案名稱
            string name = filePathName.FileName;
            // 取得裡最後一個"."的索引
            int i = name.LastIndexOf(".");
            // 取得副檔名
            string type = name.Substring(i);
            FileFtpUpload(filePathName.FileName, type, filePathName.PostedFile.ContentLength, filePathName.FileContent);
        }
        else
        {
            Response.Write("<font color='red'>請選擇上傳的檔案!</font>");
        }

    }
    // http檔案上傳
    public void FileHttpUpLoad()
    {
        // 檢查上傳檔案不為空白
        if (filePathName.FileName.LastIndexOf(".") > 0)
        {
            // 擷取檔案名稱
            string name = filePathName.FileName;
            // 取得裡最後一個"."的索引
            int i = name.LastIndexOf(".");
            // 取得副檔名
            string type = name.Substring(i);
            // 儲存檔案
            filePathName.SaveAs(upLoadPath + name + "." + type);
        }
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        if (filePathName.FileName != "")
        {
            FileHttpUpLoad();
        }
        else
        {
            Response.Write("<font color='red'>請選擇上傳的檔案!</font>");
        }
    }
    #endregion

    #region 【檔案下載】
    /// <summary>
    /// http檔案下載
    /// </summary>
    /// <param name="strTempFile">要下載檔案的路徑</param>
    /// <param name="strNewFileName">下載後,預設儲存的檔案名稱</param>
    /// <param name="strNewFileName">儲存檔案的類型</param>
    public void FileDownLoad(string strTempFile, string strNewFileName, string Type)
    {
        // 檔案下載響應設定
        string strTime = DateTime.Now.ToString("yyyyMMddHHmmss");

        FileInfo fi = new FileInfo(strTempFile);

        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ClearHeaders();

        HttpContext.Current.Response.ContentType = "application/octet-stream";

        string strFileName = HttpUtility.UrlEncode(strNewFileName) + "_" + strTime + "." + Type;

        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + strFileName);

        HttpContext.Current.Response.AppendHeader("Content-Length", fi.Length.ToString());

        // 輸出伺服器檔案,下載到用戶端
        HttpContext.Current.Response.TransmitFile(strTempFile);
        HttpContext.Current.Response.Flush();
        HttpContext.Current.Response.Close();

        // 必須終止
        HttpContext.Current.Response.End();
    }
    //  下載
    protected void Button2_Click(object sender, EventArgs e)
    {
        this.FileDownLoad(downFile, "yans", "txt");
    }

    #endregion

}
<=========================注意==============================>

如有朋友轉載,請著名原帖地址(http://www.cnblogs.com/yansheng9988)!該貼是新創貼!謝謝!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.