首页 > 其他分享 >读取ftp以base64返回到前端

读取ftp以base64返回到前端

时间:2023-06-17 16:24:56浏览次数:61  
标签:ftp 读取 base64 System var using reqFTP string

  • 需求:库中存放文件服务器的文件绝对路径文件(d:\abc\111\abc.pdf),搭建的ftp会指向d:\abc ,故ftp:/192.1.1.12:21/111/abc.pdf能取到文件。请用C#代码并base64格式返回到前端。
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using System.Data.Common;
using System.IO;
using System.Net;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            var st = GetFileByPath();
            Console.Write(st);
            Console.ReadLine();
        }  
		
		public static string GetFileByPath()
        {
            var filePath = "D:\\test\\1410\\412\\ab.pdf";
            string oldDir = @"D:\test";
            var dicFtp = JsonConvert.DeserializeObject<Dictionary<string, string>>(oldFtp);
            var ftpPath = $"ftp://192.168.192.31:21/" + filePath.Replace(oldDir, "").Replace(@"\", @"/").TrimStart('/');
            var str = DownloadFtp(ftpPath.Trim(), "", "");
            WriteLog("111☆" + str);
            return str;
        }
		
        private static string DownloadFtp(string ftpPath, string ftpUserID, string ftpPassword)
        {
            FtpWebRequest reqFTP;
            try
            {
                MemoryStream mms = new MemoryStream();
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.KeepAlive = false;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.KeepAlive = false;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                long cl = response.ContentLength;
                int bufferSize = 2048;
                int readCount;
                byte[] buffer = new byte[bufferSize];
                readCount = ftpStream.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    mms.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }
				/*若用mms.GetBuffer()转base64,有坑:得到的字节中包含已分配但未使用的字节。ToArray无此坑!!!
				* 资料:http://www.csref.cn/vs100/method/System-IO-MemoryStream-GetBuffer.html
				*/
                var res = Convert.ToBase64String(mms.ToArray());
                ftpStream.Close();
                mms.Close();
                response.Close();
                if (!string.IsNullOrWhiteSpace(res) && ftpPath.ToLower().EndsWith(".pdf"))
                {
                    return "data:application/pdf;base64," + res;//二进制转base64
                }
                else
                {
                    return res;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
  
  
        public static void WriteLog(string content, string group = "方便归类")
        { 
            //一条日志:证书链 耗时(ms):1  2019/7/12 19:36:05 
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("{0}:    {1}    {2}", group, content, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            string path = @"d:\";
            Directory.CreateDirectory(path);//创建目录(存在,不重建不报错)
            File.AppendAllText(path + DateTime.Now.ToString("yyyy-MM-dd") + ".txt", "\r\n" + sb.ToString(), Encoding.UTF8);
        } 

    } 
}

标签:ftp,读取,base64,System,var,using,reqFTP,string
From: https://www.cnblogs.com/anjun-xy/p/17487598.html

相关文章

  • Ubuntu20.04下 vsftpd.service 状态报错code=exited, status=2解决以及简单配置
    1、状态报错,启动失败 2、主要原因是ipv4和ipv6不能同时被监听,所以,注释ipv63、重启服务并且登录localhost,输入用户名和密码,显示登录成功 4、配置指定目录,确保对应的值如下anonymous_enable=NOlocal_enable=YESwrite_enable=YESchroot_local_user=YES 5、添加以下......
  • springBoot 读取application.yml及优先级
    1.回顾之前的web.xml的加载方式  2.springBoot加载application.yml方式1.Application.run方法中的ConfigurableEnvironmentenvironment=this.prepareEnvironment(listeners,bootstrapContext,applicationArguments);是准备环境,里面会加载配置文件 2.prepareEnviron......
  • 使用EWS协议读取Exchange邮件时报GSSAPI相关错
    错误信息:GSSAPIoperationfailedwitherrorGSSAPIoperationfailedwitherror-Anunsupportedmechanismwasrequested.NTLMauthenticationrequirestheGSSAPIplugin'gss-ntlmssp'错误原因:.NETCore的默认Docker映像不包含NTLM支持包(即gss-ntlmssp)。结果,由于未在......
  • python configparser读取配置文件
    #coding:utf-8importconfigparserimportosimportjsonbase_path=os.path.dirname(os.path.abspath(__file__))conf_file=os.path.join(base_path,"config.ini")defread_config():#读取配置文件信息try:cf=configparser.ConfigParser()......
  • python 读取yaml配置文件
    #coding:utf-8importyaml#pipinstallpyyamlimportosimportjsonbase_path=os.path.dirname(os.path.abspath(__file__))conf_file=os.path.join(base_path,"db.yaml")defread_yaml():#读取配置文件信息try:f=open('db.yaml&#......
  • EasyExcel读取Minio文件服务器Excel文件数据
       工具类inputstream转为MultipartFile/***inputStream转MultipartFile*@paraminputStream*@paramfileName*@return*/publicstaticFileItemcreateFileItem(InputStreaminputStream,StringfileName){FileItemFa......
  • sftp 设置仅能访问自己目录的用户
    1.创建一个目录,owner为root,权限为750或755,此处为/home/test01添加一个用户test01,home目录设置为/home/test01再创建一个子目录用于用户上传:/home/test01/upload,owner为test01,$mkdir/home/test01$chownroot:test01/home/test01$mkdir/home/test01/upload$chownt......
  • Java中使用Base64编码URL作为URL的参数
    Java中使用Base64编码URL作为URL的参数本文由arthinking发表于3年前|Java基础|暂无评论| 被围观8,004views+有时候我们需要使用一个URL作为URL地址的参数来传递,假如我们需要传递的URL含有参数,例如:/shopping/confirm.action?id=1&name=itzhai那么按......
  • 【网络知识】FTP主被动模式介绍及抓包分析
    一.FTP是什么FTP,即文件传输协议(FileTransferProtocol,FTP),基于该协议客户端与服务端可以实现共享文件、上传文件、下载文件。FTP基于TCP协议生成两个连接,一个用来控制连接,传输FTP命令,标准端口为21;另一个用于上传、下载数据,标准端口为20。FTP有两种工作模式,分别是主动模式和被动......
  • 关于服务器上部署war后怎么配置读取外部的yml文件
    第一步打成war包1.pom.xml修改为<packaging>war</packaging>2.然后就是依赖<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-tomcat</artifactId><scope>provided</scope&g......