- 需求:库中存放文件服务器的文件绝对路径文件(
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);
}
}
}