文件上传类

 using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks; namespace ImageResize
{
public class FtpClient
{
public string ftpUser = string.Empty;
public string ftpPassword = string.Empty;
public string ftpRootURL = string.Empty;
public bool isFlag = true;
public string baseFolderPath = null; public FtpClient(string url, string userid, string password)
{
this.ftpUser = userid;
this.ftpPassword = password;
this.ftpRootURL = url;
} /// <summary>
/// 文件夹上传
/// </summary>
/// <param name="sourceFolder"></param>
/// <param name="destFolder">ftpRootUrl + ftpPath</param>
/// <returns></returns>
public bool foldersUpload(string sourceFolder, string destFolder, string detailFolder)
{
bool isFolderFlag = false;
if (isFlag)
{
baseFolderPath = sourceFolder.Substring(, sourceFolder.LastIndexOf("\\"));
isFlag = false;
} string selectFolderName = sourceFolder.Replace(baseFolderPath, "").Replace("\\", "/"); if (selectFolderName != null)
{
string ftpDirectory = destFolder + selectFolderName;
if (ftpDirectory.LastIndexOf('/') < ftpDirectory.Length - )
{
ftpDirectory = ftpDirectory + "/";
}
if (!FtpDirectoryIsNotExists(ftpDirectory))
{
CreateFtpDirectory(ftpDirectory);
}
} try
{
string[] directories = Directory.EnumerateDirectories(sourceFolder).ToArray();
if (directories.Length > )
{
foreach (string d in directories)
{
foldersUpload(d, destFolder, sourceFolder.Replace(baseFolderPath, "").Replace("\\","/"));
}
} string[] files = Directory.EnumerateFiles(sourceFolder).ToArray();
if (files.Length > )
{
foreach (string s in files)
{ string fileName = s.Substring(s.LastIndexOf("\\")).Replace("\\", "/"); if(selectFolderName.Contains("/"))
{
if(selectFolderName.LastIndexOf('/') < selectFolderName.Length -)
{
selectFolderName = selectFolderName + '/';
} }
ftpRootURL = destFolder; fileUpload(new FileInfo(s), selectFolderName , fileName.Substring(,fileName.Length -)); }
}
isFolderFlag = true; }
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
return isFolderFlag;
} /// <summary>
/// 上传
/// </summary>
/// <param name="localFile">本地文件绝对路径</param>
/// <param name="ftpPath">上传到ftp的路径</param>
/// <param name="ftpFileName">上传到ftp的文件名</param>
public bool fileUpload(FileInfo localFile, string ftpPath, string ftpFileName)
{
bool success = false;
FtpWebRequest ftpWebRequest = null; FileStream localFileStream = null;
Stream requestStream = null; try
{
// 检查FTP目标存放目录是否存在
// 1.1 ftp 上目标目录
string destFolderPath = ftpRootURL + ftpPath; if (!FtpDirectoryIsNotExists(destFolderPath))
{
CreateFtpDirectory(destFolderPath);
} string uri = ftpRootURL + ftpPath + ftpFileName;
ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
ftpWebRequest.UseBinary = true; ftpWebRequest.KeepAlive = false;
ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpWebRequest.ContentLength = localFile.Length; int buffLength = ;
byte[] buff = new byte[buffLength];
int contentLen; localFileStream = localFile.OpenRead();
requestStream = ftpWebRequest.GetRequestStream(); contentLen = localFileStream.Read(buff, , buffLength);
while (contentLen != )
{
// 把内容从file stream 写入upload stream
requestStream.Write(buff, , contentLen);
contentLen = localFileStream.Read(buff, , buffLength);
} success = true;
}
catch (Exception)
{
success = false;
}
finally
{
if (requestStream != null)
{
requestStream.Close();
}
if (localFileStream != null)
{
localFileStream.Close();
}
} return success;
} /// <summary>
/// 上传文件
/// </summary>
/// <param name="localPath">本地文件地址(没有文件名)</param>
/// <param name="localFileName">本地文件名</param>
/// <param name="ftpPath">上传到ftp的路径</param>
/// <param name="ftpFileName">上传到ftp的文件名</param>
public bool fileUpload(string localPath, string localFileName, string ftpPath, string ftpFileName)
{
bool success = false;
try
{
FileInfo localFile = new FileInfo(localPath + localFileName);
if (localFile.Exists)
{
success = fileUpload(localFile, ftpPath, ftpFileName);
}
else
{
success = false;
}
}
catch (Exception)
{
success = false;
}
return success;
} /// <summary>
/// 下载文件
/// </summary>
/// <param name="localPath">本地文件地址(没有文件名)</param>
/// <param name="localFileName">本地文件名</param>
/// <param name="ftpPath">下载的ftp的路径</param>
/// <param name="ftpFileName">下载的ftp的文件名</param>
public bool fileDownload(string localPath, string localFileName, string ftpPath, string ftpFileName)
{
bool success = false;
FtpWebRequest ftpWebRequest = null;
FtpWebResponse ftpWebResponse = null;
Stream ftpResponseStream = null;
FileStream outputStream = null;
try
{
outputStream = new FileStream(localPath + localFileName, FileMode.Create);
string uri = ftpRootURL + ftpPath + ftpFileName;
ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
ftpWebRequest.UseBinary = true;
ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile;
ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
ftpResponseStream = ftpWebResponse.GetResponseStream();
long contentLength = ftpWebResponse.ContentLength;
int bufferSize = ;
byte[] buffer = new byte[bufferSize];
int readCount;
readCount = ftpResponseStream.Read(buffer, , bufferSize);
while (readCount > )
{
outputStream.Write(buffer, , readCount);
readCount = ftpResponseStream.Read(buffer, , bufferSize);
}
success = true;
}
catch (Exception)
{
success = false;
}
finally
{
if (outputStream != null)
{
outputStream.Close();
}
if (ftpResponseStream != null)
{
ftpResponseStream.Close();
}
if (ftpWebResponse != null)
{
ftpWebResponse.Close();
}
}
return success;
} /// <summary>
/// 重命名
/// </summary>
/// <param name="ftpPath">ftp文件路径</param>
/// <param name="currentFilename"></param>
/// <param name="newFilename"></param>
public bool fileRename(string ftpPath, string currentFileName, string newFileName)
{
bool success = false;
FtpWebRequest ftpWebRequest = null;
FtpWebResponse ftpWebResponse = null;
Stream ftpResponseStream = null;
try
{
string uri = ftpRootURL + ftpPath + currentFileName;
ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
ftpWebRequest.UseBinary = true;
ftpWebRequest.Method = WebRequestMethods.Ftp.Rename;
ftpWebRequest.RenameTo = newFileName; ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
ftpResponseStream = ftpWebResponse.GetResponseStream(); }
catch (Exception)
{
success = false;
}
finally
{
if (ftpResponseStream != null)
{
ftpResponseStream.Close();
}
if (ftpWebResponse != null)
{
ftpWebResponse.Close();
}
}
return success;
} /// <summary>
/// 消除文件
/// </summary>
/// <param name="filePath"></param>
public bool fileDelete(string ftpPath, string ftpName)
{
bool success = false;
FtpWebRequest ftpWebRequest = null;
FtpWebResponse ftpWebResponse = null;
Stream ftpResponseStream = null;
StreamReader streamReader = null;
try
{
string uri = ftpRootURL + ftpPath + ftpName;
ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
ftpWebRequest.KeepAlive = false;
ftpWebRequest.Method = WebRequestMethods.Ftp.DeleteFile;
ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
long size = ftpWebResponse.ContentLength;
ftpResponseStream = ftpWebResponse.GetResponseStream();
streamReader = new StreamReader(ftpResponseStream);
string result = String.Empty;
result = streamReader.ReadToEnd(); success = true;
}
catch (Exception)
{
success = false;
}
finally
{
if (streamReader != null)
{
streamReader.Close();
}
if (ftpResponseStream != null)
{
ftpResponseStream.Close();
}
if (ftpWebResponse != null)
{
ftpWebResponse.Close();
}
}
return success;
} /// <summary>
/// 文件存在检查
/// </summary>
public bool fileCheckExist(string destFolderPath, string fileName)
{
bool success = false;
FtpWebRequest ftpWebRequest = null;
WebResponse webResponse = null;
StreamReader reader = null;
try
{ ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(destFolderPath));
ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
ftpWebRequest.Method = WebRequestMethods.Ftp.ListDirectory;
ftpWebRequest.KeepAlive = false;
webResponse = ftpWebRequest.GetResponse();
reader = new StreamReader(webResponse.GetResponseStream());
string line = reader.ReadLine();
while (line != null)
{
string ftpName = "test.jpg";
if (line == ftpName)
{
success = true;
break;
}
line = reader.ReadLine();
}
}
catch (Exception)
{
success = false;
}
finally
{
if (reader != null)
{
reader.Close();
}
if (webResponse != null)
{
webResponse.Close();
}
}
return success;
} /// <summary>
/// 创建FTP文件目录
/// </summary>
/// <param name="ftpDirectory">ftp服务器上的文件目录</param>
public void CreateFtpDirectory(string ftpDirectory)
{
try
{
FtpWebRequest ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpDirectory));
ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
ftpWebRequest.UseBinary = true;
ftpWebRequest.KeepAlive = false;
ftpWebRequest.Method = WebRequestMethods.Ftp.MakeDirectory; FtpWebResponse respFTP = (FtpWebResponse)ftpWebRequest.GetResponse();
respFTP.Close();
}
catch (Exception ex)
{
Debug.WriteLine("FTP创建目录失败" + ex.Message);
} } /// <summary>
/// 获取目录下的详细信息
/// </summary>
/// <param name="localDir">本机目录</param>
/// <returns></returns>
public List<List<string>> GetDirDetails(string localDir)
{
List<List<string>> infos = new List<List<string>>();
try
{
infos.Add(Directory.GetFiles(localDir).ToList());
infos.Add(Directory.GetDirectories(localDir).ToList());
for (int i = ; i < infos[].Count; i++)
{
int index = infos[][i].LastIndexOf(@"\");
infos[][i] = infos[][i].Substring(index + );
}
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message);
}
return infos;
} public void UploadDirectory(string localDir, string ftpPath, string dirName, string ftpUser, string ftpPassword)
{
if (ftpUser == null)
{
ftpUser = "";
}
if (ftpPassword == null)
{
ftpPassword = "";
} string dir = localDir + dirName + @"\"; if (!Directory.Exists(dir))
{
return;
} //if (!CheckDirectoryExist(ftpPath, dirName))
//{
// MakeDir(ftpPath, dirName); //} List<List<string>> infos = GetDirDetails(dir); //获取当前目录下的所有文件和文件夹
//先上传文件
// MyLog.ShowMessage(dir + "下的文件数:" + infos[0].Count.ToString());
for (int i = ; i < infos[].Count; i++)
{
Console.WriteLine(infos[][i]);
// UpLoadFile(dir + infos[0][i], ftpPath + dirName + @"/" + infos[0][i], ftpUser, ftpPassword);
}
//再处理文件夹
// MyLog.ShowMessage(dir + "下的目录数:" + infos[1].Count.ToString());
for (int i = ; i < infos[].Count; i++)
{
UploadDirectory(dir, ftpPath + dirName + @"/", infos[][i], ftpUser, ftpPassword);
}
} /// <summary>
/// 判断Ftp上待上传文件存放的(文件夹)目录是否存在
/// 注意事项:目录结构的最后一个字符一定要是一个斜杠
/// </summary>
/// <param name="destFtpFolderPath">Ftp服务器上存放待上传文件的目录</param>
private bool FtpDirectoryIsNotExists(string destFolderPath)
{
try
{
var request = (FtpWebRequest)WebRequest.Create(destFolderPath);
request.Credentials = new NetworkCredential(ftpUser, ftpPassword);
request.Method = WebRequestMethods.Ftp.ListDirectory;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
response.Close();
return false;
}
else
{
response.Close();
}
}
return true;
} /// <summary>
/// 解析文件所在的路径(即当前文件所在的文件位置)
/// </summary>
/// <param name="destFilePath">需要存储在FTP服务器上的文件路径,如:ftp://192.168.1.100/LocalUser/picture1.jpg</param>
/// <returns></returns>
public string FtpParseDirectory(string destFilePath)
{
return destFilePath.Substring(, destFilePath.LastIndexOf("/"));
} // 验证文件类型
public bool IsAllowableFileType(string fileName)
{
//从web.config读取判断文件类型限制
string stringstrFileTypeLimit = string.Format(".jpeg|*.jpeg|*.*|All Files");
//当前文件扩展名是否包含在这个字符串中
if (stringstrFileTypeLimit.IndexOf(fileName.ToLower()) != -)
{
return true;
}
else
{
return false;
}
} //文件大小
public bool IsAllowableFileSize(long FileContentLength)
{
//从web.config读取判断文件大小的限制
Int32 doubleiFileSizeLimit = ; //判断文件是否超出了限制
if (doubleiFileSizeLimit > FileContentLength)
{
return true;
}
else
{
return false;
}
} }
}

FTP上传文件夹的更多相关文章

  1. shell中利用ftp 上传文件夹功能

    我们知道ftp 只能用来上传或者下载文件,一次单个或者多个,怎么实现将文件夹的上传和下载呢? 可以利用先在remote ip上建立一个相同的文件夹目录,然后将文件放到各自的目录中去 1.循环遍历出要上 ...

  2. FTP上传文件到服务器

    一.初始化上传控件. 1.我们这里用dropzone.js作为上传控件,下载地址http://www.dropzonejs.com/ 2.这里我们使用一个div元素作为dropzone载体. < ...

  3. 再看ftp上传文件

    前言 去年在项目中用到ftp上传文件,用FtpWebRequest和FtpWebResponse封装一个帮助类,这个在网上能找到很多,前台使用Uploadify控件,然后在服务器上搭建Ftp服务器,在 ...

  4. Ftp上传文件

    package net.util.common; import java.io.File; import java.io.FileInputStream; import java.io.FileOut ...

  5. PHP使用FTP上传文件到服务器(实战篇)

    我们在做开发的过程中,上传文件肯定是避免不了的,平常我们的程序和上传的文件都在一个服务器上,我们也可以使用第三方sdk上传文件,但是文件在第三方服务器上.现在我们使用PHP的ftp功能把文件上传到我们 ...

  6. java上传文件夹文件

    这里只写后端的代码,基本的思想就是,前端将文件分片,然后每次访问上传接口的时候,向后端传入参数:当前为第几块文件,和分片总数 下面直接贴代码吧,一些难懂的我大部分都加上注释了: 上传文件实体类: 看得 ...

  7. java实现上传文件夹

    我们平时经常做的是上传文件,上传文件夹与上传文件类似,但也有一些不同之处,这次做了上传文件夹就记录下以备后用. 首先我们需要了解的是上传文件三要素: 1.表单提交方式:post (get方式提交有大小 ...

  8. java+struts上传文件夹文件

    这里只写后端的代码,基本的思想就是,前端将文件分片,然后每次访问上传接口的时候,向后端传入参数:当前为第几块文件,和分片总数 下面直接贴代码吧,一些难懂的我大部分都加上注释了: 上传文件实体类: 看得 ...

  9. .net FTP上传文件

    FTP上传文件代码实现: private void UploadFileByWebClient() { WebClient webClient = new WebClient(); webClient ...

随机推荐

  1. CSS3之选择器

    总结了下CSS3新增的一些选择器. CSS3的选择器有基本选择器.属性选择器.伪类选择器几类. CSS3选择器 选择器 举例 例子描述 element1~element2 p~a 选择前面有 < ...

  2. iTunes - Forensic guys' best friend

    What chances do you think to acquire suspect's data from his/her iDevice? If suspects also use iTune ...

  3. 在vs2005中使用SVN进行版本管理

    1.软件准备 VisualSVN-Server-2.5.10.msi SVN服务端 WindowsXP-KB942288-v3-x86.exe XP中安装TortoiseSVNSVN1.8必须 Tor ...

  4. 图片轮播jQuery

          <script type="text/javascript">         //图片轮播         var bannerIndex = 0; ba ...

  5. Conditional Counting In SQL

      If you ever want to conditionally count the number of times a particular condition occurs in SQL, ...

  6. 转载:T-SQL语句大全

    一.基础 1.创建数据库 CREATE DATABASE database-name 2.删除数据库 drop database dbname 3.备份数据库 --- 创建 备份数据的 device ...

  7. Dev的DocumentManager添加窗体

    1.DocumentManager要设置自己的MdiParent属性 2.主窗体设置IsMidContainer为True 3.要生成的窗体设置MdiParent为主窗体 4.正常创建窗体,然后就可以 ...

  8. CentOS用户权限管理--su与sudo

    Linux权限管理--su与sudo 1.su用来切换登录的用户,比如当前用户为chen,可以用su zhu,并输入用户zhu的登录密码,就可以切换到用户zhu.如果一个普通用户想切换到root用户, ...

  9. [译]MongoDb生产环境注意事项

    译注: 本文是翻译MongoDB Manuel中的MongoDB Production Notes一节内容.这节内容重点关注生产环境中影响性能和可靠性的各种注意事项,值得正在部署MongoDB的工作者 ...

  10. mysql 排重查询

    GROUP BY 语句可以实现某一列的去重查询. 直接上语句: select io_dev_id from io_info where (TID=1 AND host_name='yang1') GR ...