ftp文件上传和下载
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文件上传和下载的更多相关文章
- Java实现FTP文件上传与下载
实现FTP文件上传与下载可以通过以下两种种方式实现(不知道还有没有其他方式),分别为:1.通过JDK自带的API实现:2.通过Apache提供的API是实现. 第一种方式 package com.cl ...
- .NET ftp文件上传和下载
文章参考来源地址:https://blog.csdn.net/wybshyy/article/details/52095542 本次对代码进行了一点扩展:将文件上传到ftp指定目录下,若目录不存在则创 ...
- FTP文件上传和下载(JAVA)
前文 1.使用FTP的方式进行文件的上传和下载(非SFTP) 2.本人手打,亲测,代码是最简单的,清晰易懂,需要的同学请结合自己的实际添加业务逻辑 2.第三方的jar包:import org.apac ...
- Java 实现ftp 文件上传、下载和删除
本文利用apache ftp工具实现文件的上传下载和删除.具体如下: 1.下载相应的jar包 commons-net-1.4.1.jar 2.实现代码如下: public class FtpUtils ...
- shell 和python 实现ftp文件上传或者下载
一.shell脚本 #####从ftp服务器上的/home/data 到 本地的/home/databackup#####!/bin/bashftp -n<<!open 172.168.1 ...
- FTP文件上传与下载
实现FTP文件上传与下载可以通过以下两种种方式实现(不知道还有没有其他方式),分别为:1.通过JDK自带的API实现:2.通过Apache提供的API是实现. 第一种方式:使用jdk中的ftpClie ...
- Python 基于Python实现Ftp文件上传,下载
基于Python实现Ftp文件上传,下载 by:授客 QQ:1033553122 测试环境: Ftp客户端:Windows平台 Ftp服务器:Linux平台 Python版本:Python 2.7 ...
- 【FTP】FTP文件上传下载-支持断点续传
Jar包:apache的commons-net包: 支持断点续传 支持进度监控(有时出不来,搞不清原因) 相关知识点 编码格式: UTF-8等; 文件类型: 包括[BINARY_FILE_TYPE(常 ...
- java/struts/Servlet文件下载与ftp文件上传下载
1.前端代码 使用超链接到Struts的Action或Servlet <a target="_blank" href="ftpFileAction!download ...
随机推荐
- 重载 CreateParams 方法[2]: 重载 TForm.CreateParams 方法的几个例子
这里有所有相关参数的解释: http://www.cnblogs.com/del/archive/2008/04/15/1154359.html //最大化窗口 procedure TForm1.Cr ...
- Ubuntu 14.04 Server i386 安装 Oracle11g_11.2.0.3 RAC
文档地址:doc 文档地址:doc
- 生成验证码程序C#
using System; using System.Data; using System.Configuration; using System.Collections; using System. ...
- mysql的引擎myisam和innodb的区别
1. MYISAM和INNODB的不同?答:主要有以下几点区别: a)构造上的区别 MyISAM在磁盘上存储成三个文件,其中.frm文件存储表定义:.MYD (MYData)为数据文件:. ...
- [java] java 中Unsafe类学习
java不能直接访问操作系统底层,而是通过本地方法来访问.Unsafe类提供了硬件级别的原子操作,主要提供了以下功能: 1.通过Unsafe类可以分配内存,可以释放内存: 类中提供的3个本地方法all ...
- cocos2d-x 2.2 创建项目
楼主用的是2.2版本号 曾经的版本号是要在vs中加入模版 建立项目 但新版本号更新后使用python建立项目 最好是python2.7以上 找到create_project.py文件所在路径 too ...
- Spring----Spring Boot Rest的使用方法
1.下载Google浏览器并安装插件 转载: http://chromecj.com/web-development/2015-03/401/download.html 打开Google浏览器-> ...
- Strut2------源码下载
转载: http://download.csdn.net/detail/dingkui/6858009
- 互斥锁mutex
https://blog.csdn.net/rqc112233/article/details/50015069 //g++ mute.cpp -o mute -g -lrt -lpthread #i ...
- MUI ajax数据请求(list)
服务器返回格式 { "code": "1001", "message": "查询成功", "data" ...