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. jquery获取html元素的绝对位置和相对位置的方法

    绝对位置坐标: 代码如下: $("#elem").offset().top$("#elem").offset().left 相对父元素的位置坐标: 代码如下: ...

  2. nginx配置语法

    http://baijiahao.baidu.com/s?id=1604485941272024493&wfr=spider&for=pc http://blog.csdn.net/h ...

  3. Oracle Apex 有用笔记系列 2 - 文件上传管理

    1. 页面设计 页面A有若干region, 当中一个region用于文件列表管理(包含显示,下载.删除).如图A. 在页面A有一button,点击它会调用页面B,页面B负责文件上传.如图B. 图A 图 ...

  4. 关于直播学习笔记-003-nginx-rtmp、srs、vlc、obs

    服务器 1.nginx-rtmp:https://github.com/illuspas/nginx-rtmp-win32 2.srs:https://github.com/illuspas/srs- ...

  5. python2.0_day19_充分使用Django_form实现前端操作后台数据库

    在前面的<python2.0_day19_学员管理系统之前端用户交互系统>一节中,我们实现了前端展示customer客户纪录.在<python2.0_day19_前端分页功能的实现& ...

  6. Linux 防火墙:Netfilter

    一.Netfilter 简介 (1) Netfilter 是 Linux 内置的一种防火墙机制,我们一般也称之为数据包过滤机制,而 iptables 只是操作 netfilter 的一个命令行工具(2 ...

  7. setTimeout原来有这种用途

    setTimeout有两个参数,第一个是需要执行的函数,第二个是将该函数推入UI队列的时间. 需要注意的两点: 1.第二个参数中设置的时间,是从执行setTimeout开始计算,而不是从整个函数执行完 ...

  8. url-loader与file-loader

    一开始用url-loader的时候,想着为什么npm run build的时候,不能将图片打包到build images的目录下,原来,没有自己看这样的说明: loader 后面 limit 字段代表 ...

  9. 微信小游戏 小程序与小游戏获取用户信息接口调整 wx.createUserInfoButton

    参考: 小程序•小故事(6)——微信登录能力优化 小程序•小故事(4)——获取用户信息 本篇主要是讲微信getUserInfo接口不再出现授权弹框 那么原来getUserInfo是怎么样?修改之后又是 ...

  10. Python - 3.6 学习三

    面向对象编程 面向对象编程 Object Oriented Programming 简称 OOP,是一种程序设计思想.OOP把对象作为程序的基本单元,一个对象包含了数据和操作数据的函数. 面向过程的程 ...