前期准备:

   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)!该贴是新创贴!谢谢!

posted on 2008-08-09 16:45  Stym--闫生  阅读(2128)  评论(1编辑  收藏  举报