文件上传类

 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. OSI(Open System Interconnection)网络模型

    OSI模型是国际互连网标准化组织(International Standards Organizations ISO)所定义的,为了使网络的各个层次有标准.这个模型一般被称为“ISO OSI(Open ...

  2. SQL Server T-SQL高级查询(转)

    高级查询在数据库中用得是最频繁的,也是应用最广泛的.   Ø 基本常用查询   --select select * from student; --all 查询所有 select all sex fr ...

  3. makefile 中定义宏位置需要注意一下

    CUR_DIR = $(shell pwd) CFLAGS = -g -Wall GCC = gcc GXX = g++ TARGET = exe.out SRC_FILES += $(shell f ...

  4. 使用Git上传本地项目代码到github

    前提:(1)ssh密钥(让本地与git链接) &  (2)装好gitbash 1.git中创建好库 2.文件夹中输入:git init (出现隐藏的.git文件) 3.git remote a ...

  5. css中float left与float right的使用说明

    转自:http://www.jb51.net/css/33740.html   脚本之家 No! 要注意以下几点: 1. 浮动元素会被自动设置成块级元素,相当于给元素设置了display:block( ...

  6. Android:控件布局(表格布局)TableLayout

    TableLayout继承LinearLayout 实例:用表格布局实现计算机布局>>>>>>>>>>>> 有多少个TableR ...

  7. AnyCAD C++ SDK与OpenCASCADE互操作

    AnyCAD SDK有.Net和C++两个版本,使用C++版本的AnyPlatformOcc模块可以实现与OpenCASCADE互操作. C++版本(VS2010 32bit)下载 在AOBridge ...

  8. Eclipse HibernateTools安装

    Hibernate Orm是个很强大的东东,可以将数据表映射成实体,EClipse安装了HibernateTools插件后可以生成pojo,配置xml等一系列自动化工作,为我们的开发减轻了很多. 下面 ...

  9. jquery不熟悉的方法

    1.jquery有一个筛选api find. 语法很简单,比如: HTML 代码: <p><span>Hello</span>, how are you?</ ...

  10. Java实现九九乘法表的输出

    九九乘法表一般为三角形,每个数分别和从1到自身的数相乘然后把结果列出来,即要用到两层循环,外层是从1到9for(i=1;i<=9;i++),内层是当前数和从1到自身相乘for(j=1;j< ...