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 ...
随机推荐
- OpenCV学习:实现简单的图像叠加
本实例使用简单的线性叠加方法来实现两幅图像的叠加,主要使用的知识如下: 1)线性融合 2)addWeighted函数 //! computes weighted sum of two arrays ( ...
- GIS-"地理空间大数据与AI的碰撞"学习笔记
1.关系 人工智能>机器学习>神经网络>深度学习 2.机器学习-两个过程 训练/学习过程:样本数据.学习器.模型参数 测试/预测过程:预测.预测值 3.神经网络 机器学习模拟人脑神经 ...
- Python Scrapy初步使用
1.创建爬虫工程 scrapy startproject stockproject001 2.创建爬虫项目 cd stockproject001 scrapy genspider stockinfo ...
- 使用C#语言实现一些功能
今天由于是周六,所以就没讲课啦,于是我就仔细看啦几道还没掌握的题,然后总结啦一下. 一.三级联动 像这个三级联动吧,感觉在做网站时间肯定会用到啦,但是那时间肯定不会是这样子做的啦,不可能把所有的省市区 ...
- 使用fetch出现unexpected end of input 解决方法
传统的ajax(即xmlhttprequest)由于使用叫复杂,于是js新推出了fetch来获取后台数据,无需引进jq的$.ajax,也可以使用promise的链式用法去处理回调地狱,着实很方便,在谷 ...
- Oracle类型number与PG类型numeric对比和转换策略
Oracle 11g number 任意精度数字类型 http://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT3 ...
- Change Base
Given an integer m in base B (2 ≤ B ≤ 10) (m contains no more than 1000 digits), find the value of t ...
- css3-巧用选择器 “:target”
今天(昨天)又发现一个知识盲区 css3的:target标签,之前学习的时候就是一眼扫过,说是认识了,但其实也就记了三分钟,合上书就全忘光了. 直到昨天,遇到一个有意思的题目,用css3新特性做一个类 ...
- 腾讯云分布式高可靠消息队列CMQ架构
版权声明:本文由张浩原创文章,转载请注明出处: 文章原文链接:https://www.qcloud.com/community/article/126 来源:腾云阁 https://www.qclou ...
- 高中生的IT之路-1.5西餐厅服务生
之所以说漫长的求职,是因为培训结束后半年左右没有找到工作. 每次面试结束后,得到的都是“回去等消息”,然后就杳无音信了.一次次的面试,一次次的失败,一次次查找失败的原因.总结来看主要有两点:一是没有工 ...