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 ...
随机推荐
- 百度地图api ak值
http://api.map.baidu.com/geocoder/v2/?ak=859d16285fd000feec89e9032513f8bb&callback=renderReverse ...
- linux中,查看某个进程打开的文件数?
需求描述: 今天在处理一个问题的时候,涉及到查看某个进程打开的文件数,在此记录下. 操作过程: 1.通过lsof命令查看某个特定的进程打开的文件数 [root@hadoop3 ~]# lsof -p ...
- Ubuntu 16.04 获取 root 用户权限并以 root权限登录
http://blog.csdn.net/csdn_flyyoung/article/details/52966583
- [转]ASP.NET MVC 5 - 查询Details和Delete方法
在这部分教程中,接下来我们将讨论自动生成的Details和Delete方法. 查询Details和Delete方法 打开Movie控制器并查看Details方法. public ActionResul ...
- laravel 模版引擎使用
laravel 模版引擎以 @标签 开头,以 @end标签 结尾,常用有 foreach foreachelse if for while等 1)foreach 和 foreachelse 差不到,区 ...
- django restframwork教程之Request和Response
从这一篇文章开始,我们会覆盖整个REST framwork框架的核心,接下来让我们介绍一些基础的构建块 Request 对象 REST framework 引入了一个扩展HttpRequest的请求对 ...
- LeetCode——Rectangle Area
Description:https://leetcode.com/problems/rectangle-area/ public class Solution { public int compute ...
- javascript:;禁用a标签默认功能的缺点。
在使用a标签做切换tab或者其他功能时,经常使用javascript:;来作为a标签的href来使用. 缺点: 1.在js尚未加载的情况下,点击该a标签会弹出新窗口. 2.会使gif动画失效(没经历过 ...
- 邮件欺诈与SPF防御
一.邮件欺诈: 众所周知,现在邮件的发件人是自己生成的,其实发件域名也是可以自己生成的.例如,A得知B组织的邮箱域(前提是B组织邮箱域没有配置SPF),那么A可以自己起一个邮箱服务器,配置相同的域名. ...
- you-get 下载网络上的富媒体信息
You-Get 乃一小小哒命令行程序,提供便利的方式,下载网络上的富媒体信息. 利用you-get下载这个网页的视频: $ you-get http://www.fsf.org/blogs/rms/2 ...