发布时间:2024-04-04 14:01
FTP是File Transfer Protocol(文件传输协议)的英文简称,而中文简称为“文本协议”。用于Internet上的控制文件的双向传输。同时,它也是一个应用程序(Application)。基于不同的操作系统有不同的FTP应用程序,而所有这些应用程序都遵守同一种协议以传输文件。在ftp的使用当中,用户经常遇到两个概念:“下载”(Download)和“上传”(upload)。“下载”文件就是从远程主机拷贝文件至自己的计算机上;“上传”文件就是将文件从自己的计算机中拷贝至远程主机上。用Internet语言来说,用户可通过客户机程序向(从)远程主机上传(下载)文件。
///
/// FTP的服务器地址,格式为ftp://192.168.1.234:8021/。
///
public string FTPCONSTR { get; set; }
///
/// //FTP服务器的用户名
///
private string FTPUSERID { get; set; }
///
/// //FTP服务器的密码
///
private string FTPPASSWORD { get; set; }
private string ftpIP { get; set; }
private string ftpPort { get; set; }
public FTPHelper(string ip = "IP", string username = "登录用户名", string password = "用户密码", string port = "端口")
{
FTPCONSTR = string.Format("{0}://{1}:{2}/", "ftp", ip, port);
FTPUSERID = username;
FTPPASSWORD = password;
}
///
/// 上传文件到远程ftp
///
/// 本地的文件目录
/// 文件名称
///
public bool UploadFile(string path, string name)
{
FileInfo f = new FileInfo(path);
path = FTPCONSTR + name;//这个路径是我要传到ftp目录下的这个目录下
FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
reqFtp.Method = WebRequestMethods.Ftp.UploadFile;
reqFtp.UsePassive = false;//只需要添加这一句话
reqFtp.UseBinary = true;
reqFtp.Credentials = new NetworkCredential(FTPUSERID, FTPPASSWORD);
reqFtp.KeepAlive = false;
reqFtp.Method = WebRequestMethods.Ftp.UploadFile;
reqFtp.ContentLength = f.Length;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
FileStream fs = f.OpenRead();
try
{
Stream strm = reqFtp.GetRequestStream();
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
strm.Close();
fs.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
string txtFilePath="";
try
{
OpenFileDialog openFileDialogTemp = new OpenFileDialog();
openFileDialogTemp.Title = "选择要上传的文件";
DialogResult dr = openFileDialogTemp.ShowDialog();
if (!File.Exists(openFileDialogTemp.FileName))
{
GLOBALS.msgbox("内容为空,请选择文件");
return;
}
if (dr == DialogResult.OK)
{
txtFilePath= openFileDialogTemp.FileName;
string filePath = this.txtFilePath.Text;
}
}
catch (Exception ex)
{
}
string id = DateTime.Now.ToString("yyyyMMddHHmmss");
string isPath = DateTime.Now.ToString("yyyy-MM-dd");
string filePath = txtFilePath;
string uploadUrl = isPath + "\\" + id + ".jpg";
FTPHelper FTPHelper = new FTPHelper();
bool uploadresult = FTPHelper.UploadFile(filePath, uploadUrl);