文件上传类

 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. javascript设计模式-外观模式

    也可译为门面模式.它为子系统中的一组接口提供一个一致的界面, Facade模式定义了一个高层接口,这个接口使得这一子系统更加容易使用.引入外观角色之后,使用者只需要直接与外观角色交互,使用者与子系统之 ...

  2. 从零开始安装Hadoop视频教程

    从零开始安装Hadoop视频教程 Hadoop 是一个能够对大量数据进行分布式处理的软件框架,用这种技术使得普通的PC服务器甚至一些近过时的服务器也能够发挥余热,组成大型集群系统,由于它的可伸缩性能够 ...

  3. JS常用的设计模式(16)—— 享元模式

    享元模式主要用来减少程序所需的对象个数. 有一个例子, 我们这边的前端同学几乎人手一本<JavaScript权威指南>. 从省钱的角度讲, 大约三本就够了. 放在部门的书柜里, 谁需要看的 ...

  4. jQuery实现的Div窗口震动效果实例

    本文实例讲述了jQuery实现的Div窗口震动效果.分享给大家供大家参考.具体如下: 这是一款jQuery窗口震动效果代码,在Div边框内点击一下鼠标,它就开始震动了,适用浏览器:IE8.360.Fi ...

  5. 关于overflow-y:scroll ios设备不流畅的问题

    最近做双创项目的时候因为页面有很多数据显示,所以打算让它Y轴方向滚动条的形式展现,但在测试阶段发现IOS设备滑动效果非常不理想: search by google之后找到解决办法: -webkit-o ...

  6. Java 8 Lambda表达式

    Java 8 Lambda表达式探险 http://www.cnblogs.com/feichexia/archive/2012/11/15/Java8_LambdaExpression.html 为 ...

  7. mysql事件调度器定时删除binlog

    MySQL5.1.6起Mysql增加了事件调度器(Event Scheduler),可以用做定时执行某些特定任务,来取代原先只能由Linux操作系统的计划任务来执行的工作MySQL的事件调度器可以精确 ...

  8. ERROR 1045 (28000): Access denied for user root@localhost (using password:

    错误描述: Mysql中添加用户之后可能出现登录时提示ERROR 1045 (28000): Access denied for user的错误.删除user.user中值为NULL的,或更新NULL ...

  9. onClick事件实现方式(打电话为例子)

    1.在button 中 android:onclick="call" 注意事项:①.方法的名字必须是call ②.区别大小写 ③.call方法必须接收一个View类型的参数 ④.方 ...

  10. 通过Eclipse创建SQLite数据库

    import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database ...