Asp.net MVC 从ftp服务器读取文件保存到网站本地

1 FTP连接辅助类

/// <summary>/// FTP操作单元/// </summary>public class TFTPOperationUnit{/// <summary>/// ftp地址/// </summary>private string FFTPUrl;/// <summary>/// ftp用户名/// </summary>string FFTPUserName;/// <summary>/// ftp用户密码/// </summary>string FFTPPwd;private NetworkCredential fNetworkCredential;/// <summary>/// FTP登录信息(账号,密码)/// </summary>public NetworkCredential FNetworkCredential{get{if (fNetworkCredential == null){fNetworkCredential = new NetworkCredential(FFTPUserName, FFTPPwd);}return fNetworkCredential;}}/// <summary>/// 初始化FTP/// </summary>/// <param name="aUrl">地址</param>/// <param name="aUserName">用户名</param>/// <param name="aPwd">密码</param>public TFTPOperationUnit(string aUrl = "", string aUserName = "", string aPwd = ""){FFTPUrl = aUrl;FFTPUserName = aUserName;FFTPPwd = aPwd;}/// <summary>/// ftp服务器上获得文件列表/// </summary>/// <param name="aFolderName">文件夹名称</param>/// <returns></returns>public string[] GetFolderPathFiles(string aFolderName){//ftp服务器指定文件夹路径string bFTPFolderPath = FFTPUrl + aFolderName;//文件夹下文件列表string[] bFolderPathFiles = new string[] { };StringBuilder bReadStr = new StringBuilder();FtpWebRequest bRequestFtp = null;WebResponse bResponseFtp = null;StreamReader bReadStem = null;try{//创建请求bRequestFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(bFTPFolderPath));bRequestFtp.Credentials = FNetworkCredential;bRequestFtp.UseBinary = true;bRequestFtp.Method = WebRequestMethods.Ftp.ListDirectory;//获取响应bResponseFtp = bRequestFtp.GetResponse();bReadStem = new StreamReader(bResponseFtp.GetResponseStream(), System.Text.Encoding.Default);//中文文件名string bReadStrLine = bReadStem.ReadLine();while (bReadStrLine != null){bReadStr.Append(bReadStrLine);bReadStr.Append("\n");bReadStrLine = bReadStem.ReadLine();}bReadStrLine = null;if (bReadStr.ToString().Trim() != ""){bReadStr.Remove(bReadStr.ToString().LastIndexOf('\n'), 1);bFolderPathFiles = bReadStr.ToString().Split('\n');}return bFolderPathFiles;}catch (Exception e){return bFolderPathFiles;}finally{bReadStem?.Close();bReadStem = null;bResponseFtp?.Close();bResponseFtp = null;bRequestFtp?.Abort();bRequestFtp = null;bFTPFolderPath = null;}}/// <summary>/// ftp上传文件/// </summary>/// <param name="aLocalDirPath">本地文件夹路径</param>/// <param name="aFolderName">ftp文件夹名称</param>/// <param name="aFileName">文件名称</param>/// <param name="aExtension">文件后缀</param>/// <returns></returns>public int DoFTPUpLoadFiles(string aLocalDirPath, string aFolderName, string aFileName, string aExtension){int bResult = -1;int bWaitTime = 0;string bLocalDirPath = aLocalDirPath + "\\" + aFileName + aExtension;//上传文件是否存在while (!File.Exists(bLocalDirPath) && bWaitTime < 100){Thread.Sleep(100);bWaitTime++;}if (!File.Exists(bLocalDirPath)){bResult = -1;}else{bResult = DoFtpUploadFile(bLocalDirPath, aFolderName, aFileName + aExtension);}return bResult;}/// <summary>/// 上传文件/// </summary>/// <param name="aLocalDirPath">上传文件所在路径</param>/// <param name="aFolderName">FTP文件夹名称</param>/// <param name="aFileName">FTP文件名称(含后缀)</param>/// <returns></returns>private int DoFtpUploadFile(string aLocalDirPath, string aFolderName, string aFileName){int bResult = -1;//检查ftp是否存在文件夹,没有则创建bResult = DoFtpMakeDir(aFolderName);if (bResult != 0){return bResult;}string bFTPFileFullPath = FFTPUrl + aFolderName + "/" + aFileName;FileInfo bFileInfo = null;FileStream bFileStem = null;//ftp文件所在路径Uri bUri = new Uri(bFTPFileFullPath);FtpWebRequest bFTPRequest = null;try{bFileInfo = new FileInfo(aLocalDirPath);bFileStem = bFileInfo.OpenRead();long length = bFileStem.Length;bFTPRequest = (FtpWebRequest)WebRequest.Create(bUri);bFTPRequest.Credentials = FNetworkCredential;bFTPRequest.Method = WebRequestMethods.Ftp.UploadFile;bFTPRequest.ContentLength = length;bFTPRequest.Timeout = 5 * 1000;Stream bStem = bFTPRequest.GetRequestStream();int BufferLength = 2048; //2K     byte[] bBytes = new byte[BufferLength];int i;while ((i = bFileStem.Read(bBytes, 0, BufferLength)) > 0){bStem.Write(bBytes, 0, i);}bStem.Close();bStem.Dispose();bStem = null;bBytes = null;bResult = 0;return bResult;}catch (Exception e){bResult = -1;return bResult;}finally{bFileStem?.Dispose();bFileStem = null;bFileInfo = null;bUri = null;bFileStem?.Close();bFileStem = null;bFTPRequest?.Abort();bFTPRequest = null;bFTPFileFullPath = null;}}/// <summary>/// 从ftp下载文件/// </summary>/// <param name="aFileName">文件路径</param>/// <returns></returns>public Stream DoDTPDownloadFile(string aFileName){Stream bStem = null;FtpWebResponse bFTPResponse = null;FtpWebRequest bFTPRequest = null;try{aFileName = aFileName.Replace("\\", "/");string aUrl = FFTPUrl + aFileName;bFTPRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(aUrl));bFTPRequest.UseBinary = true;bFTPRequest.Credentials = FNetworkCredential;bFTPResponse = (FtpWebResponse)bFTPRequest.GetResponse();bStem = bFTPResponse.GetResponseStream();return bStem;}catch (Exception e){bStem = null;return bStem;}finally{//不能进行释放,否则 bStem会释放。}}/// <summary>/// 在ftp创建文件夹/// </summary>/// <param name="aFolderPath">文件夹路径</param>int DoFtpMakeDir(string aFolderPath){int bResult = -1;string bFolderPath = FFTPUrl + aFolderPath;FtpWebRequest bFTPRequest = null;FtpWebResponse bFTPResponse = null;try{bFTPRequest = (FtpWebRequest)FtpWebRequest.Create(bFolderPath);bFTPRequest.Credentials = FNetworkCredential;bFTPRequest.Method = WebRequestMethods.Ftp.MakeDirectory;bFTPRequest.UseBinary = true;bFTPRequest.Proxy = null;bFTPResponse = (FtpWebResponse)bFTPRequest.GetResponse();bFTPResponse.Close();bFTPResponse = null;bResult = 0;return bResult;}catch (Exception e){//文件已存在if (e.Message.Contains("(550) 文件不可用")){bResult = 0;}else{bResult = -1;}return bResult;}finally{bFTPResponse?.Close();bFTPResponse = null;bFTPRequest?.Abort();bFTPRequest = null;}}/// <summary>/// 在ftp删除文件夹/// </summary>/// <param name="aFolderPath">文件夹路径</param>public bool DoFtpDeleteDir(string aFolderPath){FtpWebRequest bFTPRequest = null;FtpWebResponse bFTPResponse = null;try{if (string.IsNullOrWhiteSpace(aFolderPath)) return true;bFTPRequest = (FtpWebRequest)FtpWebRequest.Create(aFolderPath);bFTPRequest.Credentials = FNetworkCredential;bFTPRequest.KeepAlive = false;bFTPRequest.ContentLength = 1000;bFTPRequest.Timeout = 5 * 1000;bFTPRequest.Method = WebRequestMethods.Ftp.DeleteFile;bFTPResponse = (FtpWebResponse)bFTPRequest.GetResponse();return true;}catch (Exception e){return false;}finally{bFTPResponse?.Close();bFTPResponse = null;bFTPRequest?.Abort();bFTPRequest = null;}}}

2 WebApi接口实现

/// <summary>/// 返回ftp上文件的base64字符串/// </summary>/// <param name="PdfName"></param>/// <returns></returns>[HttpGet]public IHttpActionResult GetFTPPdfBaseStr(string PdfName) {try{TFTPOperationUnit bFTPOperationUnit = new TFTPOperationUnit("ftp://192.168.1.106:21/", "ftp", "123456");string base64Str = default(string);int bufferSize = 2048;byte[] buffer = new byte[bufferSize];using (System.IO.Stream fileStream = bFTPOperationUnit.DoDTPDownloadFile(PdfName)){int readCount;   //读取到的数据流的长度readCount =fileStream.Read(buffer, 0, bufferSize);byte[] bTmp = new byte[0];//循环加载数据,因为数据流太长,长度获取异常while (readCount > 0){bTmp = bTmp.Concat(buffer).ToArray();readCount = fileStream.Read(buffer, 0, bufferSize);}base64Str = Convert.ToBase64String(bTmp);}return Json(new { Code = 0, Msg = "查询成功", Data = base64Str });}catch (Exception e){return Json(new { Code = -1, Msg = "查询失败:" + e.Message });}}

3 MVC后台保存pdf文件

/// <summary>/// Base64字符串转文件并保存/// </summary>/// <param name="base64String">base64字符串</param>/// <param name="fileName">保存的文件名</param>/// <returns>是否转换并保存成功</returns>[HttpPost]public string Base64StringToFile(string base64String, string folder, string pdfName){try{string bPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\PDFfiles";string bFileName = pdfName + ".pdf";string fileFullPath = bPath + "\\" + folder; //文件保存路径if (!Directory.Exists(fileFullPath)){Directory.CreateDirectory(fileFullPath);}//判断是否已经存在此文件,若存在则删除if (System.IO.File.Exists(fileFullPath + "\\" + bFileName)){System.IO.File.Delete(fileFullPath + "\\" + bFileName);//return folder + "\\" + fileName;}//string strbase64 = base64String.Trim().Substring(base64String.IndexOf(",") + 1); //将‘,’以前的多余字符串删除string strbase64 = base64String;int bufferSize = 2048;MemoryStream stream = new MemoryStream(Convert.FromBase64String(strbase64));FileStream fs = new FileStream(fileFullPath + "\\" + bFileName, FileMode.OpenOrCreate, FileAccess.Write);byte[] bData = Convert.FromBase64String(strbase64);  //stream.ToArray();//fs.Write(b, 0, b.Length);//fs.Close();int readCount = stream.Read(bData, 0, bufferSize);while (readCount > 0){fs.Write(bData, 0, readCount);readCount = stream.Read(bData, 0, bufferSize);}fs.Close();fs = null;return folder + "\\" + bFileName;}catch (Exception e){return "";}}private static string logPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\PDFfiles";/// <summary>/// Base64字符串转文件并保存/// </summary>/// <param name="base64String">base64字符串</param>/// <param name="fileName">保存的文件名</param>/// <returns>是否转换并保存成功</returns>[HttpPost]public string Base64StringToFile(string base64String,string folder,string pdfName){try{string fileName = pdfName+".jpg";string fileFullPath = logPath+"\\"+folder; //文件保存路径if (!Directory.Exists(fileFullPath)){Directory.CreateDirectory(fileFullPath);}//判断是否已经存在此文件,若存在则删除if (System.IO.File.Exists(fileFullPath + "\\" + fileName)){System.IO.File.Delete(fileFullPath + "\\" + fileName);//return folder + "\\" + fileName;}//string strbase64 = base64String.Trim().Substring(base64String.IndexOf(",") + 1); //将‘,’以前的多余字符串删除string strbase64 = base64String;MemoryStream stream = new MemoryStream(Convert.FromBase64String(strbase64));FileStream fs = new FileStream(fileFullPath + "\\" + fileName, FileMode.OpenOrCreate, FileAccess.Write);byte[] b = stream.ToArray();fs.Write(b, 0, b.Length);fs.Close();return folder + "\\" + fileName;}catch (Exception e){return "";}}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/442087.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

多帧点云数据拼接合并_自动驾驶:Lidar 3D传感器点云数据和2D图像数据的融合标注...

自动驾驶汽车的发展已经见证了硬件传感器记录感官数据的容量和准确度的发展。传感器的数量增加了&#xff0c;新一代传感器正在记录更高的分辨率和更准确的测量结果。 在本文中&#xff0c;我们将探讨传感器融合如何在涉及环环相扣的数据标记过程中实现更高程度的自动化。所有自…

*【HDU - 1506】【POJ - 2559】Largest Rectangle in a Histogram(单调栈或动态规划)

题干&#xff1a; Description A histogram is a polygon composed of a sequence of rectangles aligned at a common base line. The rectangles have equal widths but may have different heights. For example, the figure on the left shows the histogram that consist…

pdf转图片记录

1 winform将pdf转图片&#xff0c;有案例&#xff0c;连接为&#xff1a;https://download.csdn.net/download/mingjing941018/20216747 2 Asp.net MVC将pdf转图片 使用Nuget安装包安装Freespire.pdf&#xff0c;控制器中相关代码&#xff1a; /// <summary>/// 将本地…

【基础知识】大数据组件HBase简述

HBase是一个开源的、面向列&#xff08;Column-Oriented&#xff09;、适合存储海量非结构化数据或半结构化数据的、具备高可靠性、高性能、可灵活扩展伸缩的、支持实时数据读写的分布式存储系统。 只是面向列&#xff0c;不是列式存储 mysql vs hbase vs clickhouse HMaster …

改变定时器获取传感器频度_广东梅州梅县压力传感器*校对

广东梅州梅县压力传感器*校对看门狗寄存器不会改变或改变不大&#xff0c;如果看门狗寄存器发生了改变或改变很大&#xff0c;则说明系统陷入“死循环”.需要进行出错处理。在工业应用中&#xff0c;严重的干扰有时会破坏中断方式控制字&#xff0c;关闭中断&#xff0c;造成看…

**【POJ - 2389】 Bull Math (高精度乘法)

题干&#xff1a; Bulls are so much better at math than the cows. They can multiply huge integers together and get perfectly precise answers ... or so they say. Farmer John wonders if their answers are correct. Help him check the bulls answers. Read in two …

nodeType的类型

1&#xff1a;元素节点   2&#xff1a;属性节点   3&#xff1a;文本节点   4&#xff1a;CDATA区段   5&#xff1a;实体应用元素   6&#xff1a;实体   7&#xff1a;表示处理指令   8&#xff1a;注释节点   9&#xff1a;最外层的Root element,包括所有其…

springboot 不响应字段为空_面试官扎心一问:Tomcat 在 SpringBoot 中是如何启动的?...

作者&#xff1a;木木匠 http://my.oschina.net/luozhou/blog/3088908前言我们知道 SpringBoot 给我们带来了一个全新的开发体验&#xff0c;我们可以直接把 web 程序达成 jar 包&#xff0c;直接启动&#xff0c;这就得益于 SpringBoot 内置了容器&#xff0c;可以直接启动&am…

【POJ - 3250 】Bad Hair Day (单调栈)

题干&#xff1a; Some of Farmer Johns N cows (1 ≤ N ≤ 80,000) are having a bad hair day! Since each cow is self-conscious about her messy hairstyle, FJ wants to count the number of other cows that can see the top of other cows heads. Each cow i has a s…

a1708硬盘转接口_资讯:希捷上架新款银河Exos系列机械硬盘,15000转+SAS协议

今日最新消息&#xff0c;希捷上架一款新品希捷银河Exos系列机械硬盘。据悉这款硬盘采用了SAS协议&#xff0c;转速高达15000RPM&#xff0c;目前公布的售价600GB为1899元RMB。据官方介绍这款希捷银河Exos系列机械硬盘为2.5英寸&#xff0c;15mm的厚度&#xff0c;最高的转速可…

ACM中关于计算几何(浮点数)的精度问题

计算几何的精度问题说到底其实是浮点数的精度问题&#xff0c;但我觉得“计算几何”比“浮点数”更能吸引眼球&#xff0c;所以选了这个标题。 1.浮点数为啥会有精度问题&#xff1a; 浮点数(以C/C为准)&#xff0c;一般用的较多的是float, double。 占字节数 数值范围 十进…

微信公众号网站开发相关记录

1 如何监听微信录音是否正常开启 wx.startRecord({success: function (ret) {alert("开始录音" JSON.stringify(ret));},fail: function (err) {alert("无法录音" JSON.stringify(err));}});

【POJ - 1182】 食物链(附超详细讲解)(并查集--种类并查集经典题)

题干&#xff1a; 动物王国中有三类动物A,B,C&#xff0c;这三类动物的食物链构成了有趣的环形。A吃B&#xff0c; B吃C&#xff0c;C吃A。 现有N个动物&#xff0c;以1&#xff0d;N编号。每个动物都是A,B,C中的一种&#xff0c;但是我们并不知道它到底是哪一种。 有人用两…

腐蚀单机怎么进_暖气片堵塞是什么原因?要怎么解决呢?

你知道散热器到底为什么堵塞吗&#xff1f;散热器堵塞了怎么办&#xff1f;下面和金旗舰散热器小编一起来看看吧~一、散热器堵塞怎么办首先&#xff0c;把进回水阀先全部关闭&#xff0c;用扳手将散热器的堵头轻轻拧开。这里需要注意的是&#xff0c;堵头对应的散热器下面要放一…

layui弹出界面空白页问题

弹出界面时&#xff0c;有时会出现空白界面&#xff0c;应该如何处理&#xff1f; 1 尝试解决方式&#xff1a;在open方法的success回调方法中&#xff0c;获取当前iframe高度&#xff0c;重新赋予新的高度&#xff1b; let ifr layero.find(iframe)[0]; let bHeight ifr.s…

vspy如何在图形面板显示报文_设备实时状态监控:如何进行工业生产设备数据采集?...

设备实时状态监控&#xff1a;如何进行工业生产设备数据采集&#xff1f;数据采集(DAQ)&#xff0c;是指从传感器和其它待测设备等模拟和数字被测单元中自动采集非电量或者电量信号,送到上位机中进行分析&#xff0c;处理。慧都设备数据采集系统解决方案工业生产设备数据采集是…

【POJ - 2236】Wireless Network (并查集)

题干&#xff1a; An earthquake takes place in Southeast Asia. The ACM (Asia Cooperated Medical team) have set up a wireless network with the lap computers, but an unexpected aftershock attacked, all computers in the network were all broken. The computers …

如何使用微信公众平台测试号进行系统开发

申请一个测试号&#xff1a;入口修改测试公众号自定义菜单&#xff08;使用微信公众平台接口调试工具&#xff09;网站开发&#xff0c;进行部署网站测试

【POJ - 1751】Highways (最小生成树)

题干&#xff1a; The island nation of Flatopia is perfectly flat. Unfortunately, Flatopia has a very poor system of public highways. The Flatopian government is aware of this problem and has already constructed a number of highways connecting some of the …

jupyter怎么安装jieba_AI工具:Anaconda中Jupyter不能import已安装module问题解决

jupyter模式下写代码时,通过pip install package命令行安装package完成之后,无法在jupyter模式下import &#xff0c;这是个通用的问题&#xff0c;我这里遇到的是import jieba&#xff0c;可能import 别的package也会出现&#xff0c;记录下&#xff0c;也花了点时间排查。。。…