你的位置:首页 > ASP.net教程

[ASP.net教程].net ftp上传文件方法


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

namespace DlnOffice.general.netdisk
{
public partial class fileupload2 : System.Web.UI.Page
{

//这三个常量是从webconfig获取
private string ftpServerIP = ConfigurationManager.AppSettings["ftpServerIP"];
private string ftpUserID = ConfigurationManager.AppSettings["ftpUserID"];
private string ftpPassword = ConfigurationManager.AppSettings["ftpPassword"];
protected void Page_Load(object sender, EventArgs e)
{

}
protected void LinkButton1_Click(object sender, EventArgs e)
{
up_FTP(FileUpload1);
//up_FTP(FileUpload2);
Response.Write("<script>alert('完成');window.location.href ='fileupload2.aspx'</script>");

//else
//{
// Response.Write("<script>alert('未选择文件');</script>");
// return;
//}
}

public void up_FTP(FileUpload fu)
{
string AppPath = (base.Request.QueryString["parent_folder"] != null) ? base.Request.QueryString["parent_folder"].ToString() : "/信息科/常用软件";
if (string.IsNullOrEmpty(AppPath))
{
base.Response.Redirect("index.aspx");
return;
}
//文件上传地址根目录,这里通过IIS架设本地主机为FTP服务器
//string FileSaveUri = @"ftp://127.0.0.1/";
string FileSaveUri = @"ftp://" + ftpServerIP + AppPath + "/";
//FTP用户名密码,就是本机的用户名密码
string ftpUser = ftpUserID;
string ftpPassWord = ftpPassword;
Stream requestStream = null;
Stream fileStream = null;
FtpWebResponse uploadResponse = null;//创建FtpWebResponse实例uploadResponse
//Btn_Upload.
if (fu.HasFile)
{
//获取文件长度
int FileLength = fu.PostedFile.ContentLength;
//限制上传文件最大不能超过1G
if (FileLength < 1024 * 1024 * 1024)
{
try
{

//格式化为URI
Uri uri = new Uri(FileSaveUri + Path.GetFileName(fu.PostedFile.FileName));
FtpWebRequest uploadRequest = (FtpWebRequest)WebRequest.Create(uri);//创建FtpWebRequest实例uploadRequest
uploadRequest.Method = WebRequestMethods.Ftp.UploadFile;//将FtpWebRequest属性设置为上传文件
uploadRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);//认证FTP用户名密码
requestStream = uploadRequest.GetRequestStream();//获得用于上传FTP的流
byte[] buffer = new byte[FileLength];
fileStream = fu.PostedFile.InputStream;//截取FileUpload获取的文件流,作为上传FTP的流
fileStream.Read(buffer, 0, FileLength);
requestStream.Write(buffer, 0, FileLength);//将buffer写入流
requestStream.Close();
uploadResponse = (FtpWebResponse)uploadRequest.GetResponse();//返回FTP服务器响应,上传完成
//上传成功

}
catch (Exception ex)
{
//无法上传
Response.Write("<script>alert('无法上传');</script>");
return;
}
finally
{
if (uploadResponse != null)
uploadResponse.Close();
if (fileStream != null)
fileStream.Close();
if (requestStream != null)
requestStream.Close();
}
}//end if #FileLength#
else
{
//上传文件过大
Response.Write("<script>alert('上传文件过大,文件不得超过1G');</script>");
return;
}
}//end if #FileUpload.HasFile#
else
{
//未选择文件
return;
}
}
}
}