using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
using System.IO; namespace FtpHelper
{
public delegate void DownloadCompleteHandler();
public delegate void DownloadProgressHandler(int bytesRead, int totalBytes);
/// <summary>
/// ftp下载类
/// </summary>
public class FtpDownload
{
public DownloadCompleteHandler CompleteCallback;
public DownloadProgressHandler ProgressCallback;
private FtpWebRequest reqFTP = null;
private FtpWebResponse resFTP = null;
private Thread mThread = null;
//下载文件到本地的存储路径
private string sFileName = string.Empty; public string DlFileName
{
get { return sFileName; }
set { sFileName = value; }
}
private FileStream outputStream = null;
private Stream ftpStream = null;
public bool IsComplete = false;
//用于终止下载
private bool stopFlag = false;
//从Ftp下载的文件路径,示例:"ftp://192.168.2.200/Project/asss.xls"
private string sFtpUrl = string.Empty;
private string sFtpUser = string.Empty;
private string sFtpPassword = string.Empty;
public int BytesProcessed; public FtpDownload(string sUrlPath, string ftpUser, string ftpPassword)
{
sFtpUrl = sUrlPath;
sFtpUser = ftpUser;
sFtpPassword = ftpPassword; }
/// <summary>
/// 后台下载
/// </summary>
public void DownloadBackgroundFile()
{
if (CompleteCallback == null)
throw new ArgumentException("No download complete callback specified.");
//实例化下载线程
mThread = new Thread(new ThreadStart(Download));
mThread.Name = "WebDownload.dlThread";
mThread.IsBackground = true;
mThread.CurrentUICulture = Thread.CurrentThread.CurrentUICulture;
//开启后台下载线程
mThread.Start();
}
protected void Download()
{
try
{
if (stopFlag)
{
IsComplete = true;
return;
}
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(sFtpUrl));
reqFTP.UseBinary = true;
reqFTP.Proxy = null;
reqFTP.UsePassive = false;
reqFTP.Credentials = new NetworkCredential(sFtpUser, sFtpPassword);
if (stopFlag)
{
IsComplete = true;
return;
}
resFTP = (FtpWebResponse)reqFTP.GetResponse();
ftpStream = resFTP.GetResponseStream();
long ContentLength = resFTP.ContentLength;
int bufferSize = ;
byte[] readBuffer = new byte[bufferSize];
outputStream = new FileStream(sFileName, FileMode.Create);
while (true)
{
if (stopFlag)
{
IsComplete = true;
return;
}
// Pass do.readBuffer to BeginRead.
int bytesRead = ftpStream.Read(readBuffer, , bufferSize);
if (bytesRead <= )
break;
outputStream.Write(readBuffer, , bytesRead);
BytesProcessed += bytesRead;
OnProgressCallback(BytesProcessed, (int)ContentLength);
} OnCompleteCallback();
}
catch (Exception ex)
{
try
{
// Remove broken file download
if (outputStream != null)
{
outputStream.Close();
outputStream = null;
}
if (sFileName != null && sFileName.Length > )
{
File.Delete(sFileName);
}
}
catch (Exception)
{
}
Logger.Log.Write(ex.Message);
}
finally
{
if (resFTP != null)
{
resFTP.Close();
resFTP = null;
}
if (ftpStream != null)
{
ftpStream.Close();
ftpStream.Dispose();
}
if (outputStream != null)
{
outputStream.Close();
outputStream.Dispose();
}
IsComplete = true;
} } private void OnProgressCallback(int bytesRead, int totalBytes)
{
if (ProgressCallback != null)
{
ProgressCallback(bytesRead, totalBytes);
}
}
private void OnCompleteCallback()
{
if (CompleteCallback != null)
{
CompleteCallback();
}
}
/// 终止当前下载
/// </summary>
public void Cancel()
{
CompleteCallback = null;
ProgressCallback = null;
if (mThread != null && mThread != Thread.CurrentThread)
{
if (mThread.IsAlive)
{
// Log.Write(Log.Levels.Verbose, "WebDownload.Cancel() : stopping download thread...");
stopFlag = true;
if (!mThread.Join())
{
//Log.Write(Log.Levels.Warning, "WebDownload.Cancel() : download thread refuses to die, forcing Abort()");
mThread.Abort();
}
}
mThread = null;
}
} public void Dispose()
{
if (mThread != null && mThread != Thread.CurrentThread)
{
if (mThread.IsAlive)
{
// Log.Write(Log.Levels.Verbose, "WebDownload.Dispose() : stopping download thread...");
stopFlag = true;
if (!mThread.Join())
{
// Log.Write(Log.Levels.Warning, "WebDownload.Dispose() : download thread refuses to die, forcing Abort()");
mThread.Abort();
}
}
mThread = null;
} if (reqFTP != null)
{
reqFTP.Abort();
reqFTP = null;
} if (outputStream != null)
{
outputStream.Close();
outputStream = null;
} //if (DownloadStartTime != DateTime.MinValue)
// OnDebugCallback(this); GC.SuppressFinalize(this);
}
}
}
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
using System.IO; namespace FtpHelper
{
public delegate void UploadCompleteHandler();
public delegate void UploadProgressHandler(int bytesRead, int totalBytes);
public class FtpUpload
{
public UploadCompleteHandler CompleteCallback;
public UploadProgressHandler ProgressCallback;
private FtpWebRequest reqFTP;
private FtpWebResponse resFTP;
private Thread mThread = null;
//本地文件路径
private string sFileName = string.Empty; public string UlFileName
{
get { return sFileName; }
set { sFileName = value; }
}
private Stream uploadStream = null;
public bool IsComplete = false;
//用于终止上传
private bool stopFlag = false;
//上传到Ftp路径,示例:"ftp://192.168.2.200/Project/asss.xls"
private string sFtpUrl = string.Empty;
private string sFtpUser = string.Empty;
private string sFtpPassword = string.Empty;
private int BytesProcessed;
public FtpUpload(string sUrlPath, string ftpUser, string ftpPassword)
{
sFtpUrl = sUrlPath;
sFtpUser = ftpUser;
sFtpPassword = ftpPassword;
} /// <summary>
/// 后台上传
/// </summary>
public void UploadBackgroundFile()
{
if (CompleteCallback == null)
throw new ArgumentException("未定义上传成功后执行的回调函数!");
//实例化下载线程
mThread = new Thread(new ThreadStart(Upload));
mThread.Name = "upload";
mThread.IsBackground = true;
mThread.CurrentUICulture = Thread.CurrentThread.CurrentUICulture;
//开启后台下载线程
mThread.Start();
}
protected void Upload()
{
using (FileStream fileStream = new FileStream(sFileName, FileMode.Open))
{
byte[] fsdata = new byte[Convert.ToInt32(fileStream.Length)];
fileStream.Read(fsdata, , Convert.ToInt32(fileStream.Length));
try
{
if (stopFlag)
{
IsComplete = true;
return;
}
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(sFtpUrl));
reqFTP.UseBinary = true;
reqFTP.Proxy = null;
reqFTP.UsePassive = false;
reqFTP.Credentials = new NetworkCredential(sFtpUser, sFtpPassword);
if (stopFlag)
{
IsComplete = true;
return;
} reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.ContentLength = fileStream.Length; int buffLength = ;
byte[] buffer = new byte[buffLength]; uploadStream = reqFTP.GetRequestStream();
fileStream.Position = ;
while (true)
{
if (stopFlag)
{
IsComplete = true;
return;
}
int bytesRead = fileStream.Read(buffer, , buffLength);
if (bytesRead <= )
break;
uploadStream.Write(buffer, , bytesRead); BytesProcessed += bytesRead;
OnProgressCallback(BytesProcessed, (int)reqFTP.ContentLength);
}
OnCompleteCallback();
}
catch (Exception ex)
{
if (fileStream != null)
{
fileStream.Close();
//fileStream = null;
}
Logger.Log.Write(ex.Message);
//throw;
}
finally
{
if (uploadStream != null)
{
uploadStream.Close();
uploadStream.Dispose();
}
reqFTP = null;
IsComplete = true;
}
}
}
private void OnProgressCallback(int bytesRead, int totalBytes)
{
if (ProgressCallback != null)
{
ProgressCallback(bytesRead, totalBytes);
}
}
private void OnCompleteCallback()
{
if (CompleteCallback != null)
{
CompleteCallback();
}
}
/// 终止当前下载
/// </summary>
public void Cancel()
{
CompleteCallback = null;
ProgressCallback = null;
if (mThread != null && mThread != Thread.CurrentThread)
{
if (mThread.IsAlive)
{
// Log.Write(Log.Levels.Verbose, "WebDownload.Cancel() : stopping download thread...");
stopFlag = true;
if (!mThread.Join())
{
//Log.Write(Log.Levels.Warning, "WebDownload.Cancel() : download thread refuses to die, forcing Abort()");
mThread.Abort();
}
}
mThread = null;
}
} public void Dispose()
{
if (mThread != null && mThread != Thread.CurrentThread)
{
if (mThread.IsAlive)
{
// Log.Write(Log.Levels.Verbose, "WebDownload.Dispose() : stopping download thread...");
stopFlag = true;
if (!mThread.Join())
{
//Log.Write(Log.Levels.Warning, "WebDownload.Dispose() : download thread refuses to die, forcing Abort()");
mThread.Abort();
}
}
mThread = null;
} if (reqFTP != null)
{
reqFTP.Abort();
reqFTP = null;
} //if (DownloadStartTime != DateTime.MinValue)
// OnDebugCallback(this);
GC.SuppressFinalize(this);
} }
}

ftp文件上传和下载的更多相关文章

  1. Java实现FTP文件上传与下载

    实现FTP文件上传与下载可以通过以下两种种方式实现(不知道还有没有其他方式),分别为:1.通过JDK自带的API实现:2.通过Apache提供的API是实现. 第一种方式 package com.cl ...

  2. .NET ftp文件上传和下载

    文章参考来源地址:https://blog.csdn.net/wybshyy/article/details/52095542 本次对代码进行了一点扩展:将文件上传到ftp指定目录下,若目录不存在则创 ...

  3. FTP文件上传和下载(JAVA)

    前文 1.使用FTP的方式进行文件的上传和下载(非SFTP) 2.本人手打,亲测,代码是最简单的,清晰易懂,需要的同学请结合自己的实际添加业务逻辑 2.第三方的jar包:import org.apac ...

  4. Java 实现ftp 文件上传、下载和删除

    本文利用apache ftp工具实现文件的上传下载和删除.具体如下: 1.下载相应的jar包 commons-net-1.4.1.jar 2.实现代码如下: public class FtpUtils ...

  5. shell 和python 实现ftp文件上传或者下载

    一.shell脚本 #####从ftp服务器上的/home/data 到 本地的/home/databackup#####!/bin/bashftp -n<<!open 172.168.1 ...

  6. FTP文件上传与下载

    实现FTP文件上传与下载可以通过以下两种种方式实现(不知道还有没有其他方式),分别为:1.通过JDK自带的API实现:2.通过Apache提供的API是实现. 第一种方式:使用jdk中的ftpClie ...

  7. Python 基于Python实现Ftp文件上传,下载

    基于Python实现Ftp文件上传,下载   by:授客 QQ:1033553122 测试环境: Ftp客户端:Windows平台 Ftp服务器:Linux平台 Python版本:Python 2.7 ...

  8. 【FTP】FTP文件上传下载-支持断点续传

    Jar包:apache的commons-net包: 支持断点续传 支持进度监控(有时出不来,搞不清原因) 相关知识点 编码格式: UTF-8等; 文件类型: 包括[BINARY_FILE_TYPE(常 ...

  9. java/struts/Servlet文件下载与ftp文件上传下载

    1.前端代码 使用超链接到Struts的Action或Servlet <a target="_blank" href="ftpFileAction!download ...

随机推荐

  1. 静默安装oracle 11g,环境预检查时报错,SEVERE: [FATAL] PRVF-0002 : 无法检索本地节点名

    环境描述: 操作系统:Redhat 6.6_x64 oracle:11.2.0.4 x64 问题描述: 今天在安装oracle 11g的数据库,在进行预安装环境检查的时候,报下面的错误: [oracl ...

  2. windows,cmd中,如何切换到磁盘的根目录下

    需求描述: 在windows的cmd中操作,有的时候也会遇到切换了很多的目录,然后需要切换到根目录的情况 操作过程: 1.通过cd \的方式,切换回当前磁盘的根目录下 备注:未切换之前,在Driver ...

  3. C#------?和??运算符的作用

    转载: http://www.cnblogs.com/zfanlong1314/archive/2012/02/26/2390456.html 1.?的作用 在处理数据库和其他包含不可赋值的元素的数据 ...

  4. 更改嵌入式Linux中开机画面----左上角小企鹅图标

    一直想给嵌入式仪表加个开机LOGO,但是没有找到更换的方法.最近在网上收集了一些文章,整理一下一共自己参考.目前也还没有试过这种方法究竟是否可以.但察看Kernel源代码可以知道,Linux-2.6的 ...

  5. CentOS-6.3安装配置Nginx--【测试已OK】

    安装说明 系统环境:CentOS-6.3软件:nginx-1.2.6.tar.gz安装方式:源码编译安装 安装位置:/usr/local/nginx 下载地址:http://nginx.org/en/ ...

  6. phpstrom配置

  7. oracle数据库sql比较日期

    select * from cc_random_check_info t where check_time > to_date('2016-09-09','yyyy-MM--dd')

  8. Runtime 运行时之一:消息转发

    解释一 上一篇文章咱们提到了Runtime的消息传递机制,主要围绕三个C语言API来展开进行的.这篇文章我将从另外三个方法来描述Runtime中另一个特性:消息转发机制. 一.消息转发机制 当向某个对 ...

  9. 国内linux 镜像

    北京理工大学开源软件镜像服务mirrors.ustc.edu.cn 开源中国社区软件镜像下载资源库mirrors.oss.org.cn 阿里云开源镜像站mirrors.aliyun.com<ig ...

  10. Android技巧分享——Android开发超好用工具吐血推荐(转)

    内容中包含 base64string 图片造成字符过多,拒绝显示