首页 > 编程语言 >C# base64转pdf + 上传至指定url

C# base64转pdf + 上传至指定url

时间:2024-09-23 09:28:38浏览次数:1  
标签:sb string C# base64 System url path new

base64 to pdf

  1 using System;
  2 using System.Collections.Generic;
  3 using System.IO;
  4 using System.Linq;
  5 using System.Text;
  6 using System.Threading.Tasks;
  7 
  8 namespace HS.Common.Helper
  9 {
 10     public class PdfHelper
 11     {
 12         //定义一个用于保存静态变量的实例
 13         private static PdfHelper instance = null;
 14         //定义一个保证线程同步的标识
 15         private static readonly object locker = new object();
 16         //构造函数为私有,使外界不能创建该类的实例
 17         private PdfHelper() { }
 18         public static PdfHelper Instance
 19         {
 20             get
 21             {
 22                 if (instance == null)
 23                 {
 24                     lock (locker)
 25                     {
 26                         if (instance == null) instance = new PdfHelper();
 27                     }
 28                 }
 29                 return instance;
 30             }
 31         }
 32 
 33         public void ConvertBase64ToPdf(string base64String, string outputPath)
 34         {
 35             base64String = base64String.Replace("data:application/pdf;filename=generated.pdf;base64,", string.Empty);
 36             base64String = base64String.Replace("data:application/pdf;base64,", string.Empty);
 37             // 将base64字符串转换为字节数组
 38             byte[] pdfBytes = Convert.FromBase64String(base64String);
 39             //if (!Directory.Exists(outputPath)) Directory.CreateDirectory(outputPath);
 40             //File.WriteAllBytes(@"c:\test.Pdf", imageBytes);//保存pdf文件
 41             // 将字节数组写入到PDF文件
 42             File.WriteAllBytes(outputPath, pdfBytes);
 43         }
 44 
 45         /// <summary>
 46         /// base64 转PDF
 47         /// </summary>
 48         /// <param name="base64Content"></param>
 49         /// <param name="filePath"></param>
 50         public string Base64StringToPdf(string base64Content, string filePath)
 51         {
 52             try
 53             {
 54                 base64Content = base64Content.Replace("data:application/pdf;filename=generated.pdf;base64,", string.Empty);
 55                 base64Content = base64Content.Replace("data:application/pdf;base64,", string.Empty);
 56 
 57                 string base64ContentData = base64Content.Trim().Replace("%", "").Replace(",", "").Replace(" ", "+");
 58                 if (base64ContentData.Length % 4 > 0)
 59                 {
 60                     base64ContentData = base64ContentData.PadRight(base64ContentData.Length + 4 - base64ContentData.Length % 4, '=');
 61                 }
 62                 byte[] bytes = Convert.FromBase64String(base64ContentData);
 63 
 64                 string location = filePath;
 65                 System.IO.FileStream stream = new FileStream(location, FileMode.CreateNew);
 66                 System.IO.BinaryWriter writer = new BinaryWriter(stream);
 67                 writer.Write(bytes, 0, bytes.Length);
 68                 writer.Close();
 69 
 70             }
 71             catch (Exception ex)
 72             {
 73             }
 74             return filePath;
 75         }
 76 
 77 
 78         //public string GetDownPdftoBase64(string url, string json)
 79         //{
 80         //    HttpWebResponse httprec = InsuranceSSXHttpHelp.CreateGetHttpResponse(url, 30, "", null);
 81         //    string filename = System.DateTime.Now.ToString("yyyyMMddHHmmssfff");
 82         //    string path = System.Environment.CurrentDirectory + @"\temp" + @"\" + System.DateTime.Now.ToString("yyyyMMdd") + @"\print\";
 83         //    string filepath = InsuranceSSXHttpHelp.HttpDownloadPrint(httprec, path, filename);
 84         //    return Base64StringByPdf(filepath);
 85         //}
 86 
 87         /// <summary>
 88         /// base64 to pdf 
 89         /// </summary>
 90         /// <param name="base64"></param>
 91         /// <param name="path">文件路径</param>
 92         /// <param name="filename">文件名称</param>
 93         /// <returns></returns>
 94         public string Base64ToPdf(string base64, string path, string filename)
 95         {
 96             path = path + filename;
 97             base64 = base64.Replace("data:application/pdf;filename=generated.pdf;base64,", string.Empty);
 98             base64 = base64.Replace("data:application/pdf;base64,", string.Empty);
 99             byte[] bytes = Convert.FromBase64String(base64);
100 
101             FileStream stream = new FileStream(path, FileMode.CreateNew);
102             BinaryWriter writer = new BinaryWriter(stream);
103             writer.Close();
104             return path;
105         }
106 
107         /// <summary>
108         /// file to base64
109         /// </summary>
110         /// <param name="file"></param>
111         /// <returns></returns>
112         public string Base64StringByPdf(string file)
113         {
114             byte[] bytes = null;
115             FileStream fileStream = new FileStream(file, FileMode.Open);
116             bytes = new byte[fileStream.Length]; fileStream.Read(bytes, 0, bytes.Length);
117             fileStream.Close();
118             return Convert.ToBase64String(bytes);
119         }
120 
121 
122         public string UploadBase64ToPdf(string url, string base64)
123         {
124             string path = Environment.CurrentDirectory + @"\GSYBTEMP" + @"\" + System.DateTime.Now.ToString("yyyyMMdd") + @"\";
125             if (!Directory.Exists(path)) Directory.CreateDirectory(path);
126 
127             string filename = "GSYB"+DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".pdf";
128             //path = Base64ToPdf(base64, path, filename);
129             ConvertBase64ToPdf(base64, path+filename);
130             
131             string temp = FileHelper.Instance.UploadFile(url, path+ filename, filename);
132 
133             if (Directory.Exists(path)) Directory.Delete(path,true);
134             return temp;
135         }
136 
137     }
138 }

上传文件至指定位置

  1 using System;
  2 using System.Collections.Generic;
  3 using System.IO;
  4 using System.Linq;
  5 using System.Net;
  6 using System.Text;
  7 using System.Threading.Tasks;
  8 
  9 namespace HS.Common.Helper
 10 {
 11     public class FileHelper
 12     {
 13         //定义一个用于保存静态变量的实例
 14         private static FileHelper instance = null;
 15         //定义一个保证线程同步的标识
 16         private static readonly object locker = new object();
 17         //构造函数为私有,使外界不能创建该类的实例
 18         private FileHelper() { }
 19         public static FileHelper Instance
 20         {
 21             get
 22             {
 23                 if (instance == null)
 24                 {
 25                     lock (locker)
 26                     {
 27                         if (instance == null) instance = new FileHelper();
 28                     }
 29                 }
 30                 return instance;
 31             }
 32         }
 33 
 34         /// <summary>
 35         /// 上传文件
 36         /// </summary>
 37         /// <param name="address">url</param>
 38         /// <param name="fileNamePath">本地文件夹路径</param>
 39         /// <param name="saveName">文件名称</param>
 40         /// <returns></returns>
 41         public string UploadFile(string address, string fileNamePath, string saveName)
 42         {
 43             string returnValue = "";
 44             // 要上传的文件  
 45             FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
 46             BinaryReader r = new BinaryReader(fs);
 47             //时间戳  
 48             string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
 49             byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n");
 50             //请求头部信息  
 51             StringBuilder sb = new StringBuilder();
 52             sb.Append("--");
 53             sb.Append(strBoundary);
 54             sb.Append("\r\n");
 55             sb.Append("Content-Disposition: form-data; name=\"");
 56             sb.Append("file");
 57             sb.Append("\"; filename=\"");
 58             sb.Append(saveName);
 59             sb.Append("\"");
 60             sb.Append("\r\n");
 61             sb.Append("Content-Type: ");
 62             sb.Append("application/octet-stream");
 63             sb.Append("\r\n");
 64             sb.Append("\r\n");
 65             string strPostHeader = sb.ToString();
 66             byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader);
 67             // 根据uri创建HttpWebRequest对象  
 68             HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(address));
 69             httpReq.Method = "POST";
 70             //对发送的数据不使用缓存  
 71             httpReq.AllowWriteStreamBuffering = false;
 72             //设置获得响应的超时时间(300秒)  
 73             httpReq.Timeout = 60000;
 74             httpReq.ReadWriteTimeout = 60000;
 75             httpReq.ContentType = "multipart/form-data; boundary=" + strBoundary;
 76             httpReq.Accept = "application/json";
 77             long length = fs.Length + postHeaderBytes.Length + boundaryBytes.Length;
 78             long fileLength = fs.Length;
 79             httpReq.ContentLength = length;
 80             try
 81             {
 82                 //每次上传4k  
 83                 int bufferLength = 10240;
 84                 byte[] buffer = new byte[bufferLength];
 85                 //已上传的字节数  
 86                 long offset = 0;
 87                 //开始上传时间  
 88                 DateTime startTime = DateTime.Now;
 89                 int size = r.Read(buffer, 0, bufferLength);
 90                 Stream postStream = httpReq.GetRequestStream();
 91                 //发送请求头部消息  
 92                 postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
 93                 while (size > 0)
 94                 {
 95                     postStream.Write(buffer, 0, size);
 96                     size = r.Read(buffer, 0, bufferLength);
 97                 }
 98                 //添加尾部的时间戳  
 99                 postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
100                 postStream.Close();
101                 //获取服务器端的响应  
102                 WebResponse webRespon = httpReq.GetResponse();
103                 Stream s = webRespon.GetResponseStream();
104                 StreamReader sr = new StreamReader(s);
105                 //读取服务器端返回的消息  
106                 String sReturnString = sr.ReadLine();
107                 s.Close();
108                 sr.Close();
109                 return sReturnString;
110             }
111             catch (Exception ex)
112             {
113                 returnValue = -1 + "@" + ex.ToString();
114             }
115             finally
116             {
117                 fs.Close();
118                 r.Close();
119             }
120             return returnValue;
121         }
122 
123         /// <summary>
124         /// 删除指定目录及文件
125         /// </summary>
126         /// <param name="pathDir"></param>
127         public void DelFullPath(string pathDir)
128         {
129             try
130             {
131                 DirectoryInfo dir = new DirectoryInfo(pathDir);
132                 FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //返回目录中所有文件和子目录
133                 foreach (FileSystemInfo i in fileinfo)
134                 {
135                     if (i is DirectoryInfo)            //判断是否文件夹
136                     {
137                         DirectoryInfo subdir = new DirectoryInfo(i.FullName);
138                         subdir.Delete(true);          //删除子目录和文件
139                     }
140                     else
141                     {
142                         File.Delete(i.FullName);      //删除指定文件
143                     }
144                 }
145             }
146             catch (Exception e)
147             {
148                 throw;
149             }
150         }
151 
152     }
153 }

调用方式:

string  base64 = PubVariable.Instance.JsonPdfFileBase64;
string uploadUrl = "https://dev.his.yfttech.cn/hs/openplatform/epc_client/callback/upload";
PdfHelper.Instance.UploadBase64ToPdf(uploadUrl, base64 );

标签:sb,string,C#,base64,System,url,path,new
From: https://www.cnblogs.com/YYkun/p/18426344

相关文章

  • 为何我安装完提示这个报错?:Array and string offset access syntax with curly braces
    错误信息 Arrayandstringoffsetaccesssyntaxwithcurlybracesisdeprecated 表明你在使用的PHP版本较高,而你的程序代码中使用了一些在较新版本中已弃用的语法。具体来说,这是PHP7.4及以上版本对数组和字符串偏移量访问语法 {} 的弃用警告。解决方案1.降低PHP......
  • JavaScript基础内容
    JavaScript字面量在编程语言中,一般固定值称为字面量,如3.14。数字(Number)字面量可以是整数或者是小数,或者是科学计数(e)。数组(Array)字面量定义一个数组:[40,100,1,5,25,10]对象(Object)字面量定义一个对象:{firstName:"John",lastName:"Doe",age:50,eyeColor:"blue"......
  • 【TS】TypeScript内置条件类型-ReturnType
    ReturnType在TypeScript中,ReturnType是一个内置的条件类型(ConditionalType),它用于获取一个函数返回值的类型。这个工具类型非常有用,特别是当你需要引用某个函数的返回类型,但又不想直接写出那个具体的类型时。ReturnType的基本语法如下:typeReturnType<Textends(...args:an......
  • 为何生成静态页的时候或者上传附件过程中有报错:Maximum execution time of 30 seconds
    错误信息 Maximumexecutiontimeof30secondsexceeded 表明PHP脚本的执行时间超过了服务器设定的最大执行时间限制。这通常发生在生成静态页面或上传大文件等耗时较长的操作中。解决方案方法一:修改 php.ini 文件找到 php.ini 文件:通常 php.ini 文件位于服务......
  • JS输出为[object object] 如何解决以及原因
    参考文档:https://blog.csdn.net/weixin_48141487/article/details/121758541 问题描述项目中,欲在控制台输出变量res(自定义对象)查看数据,代码为:console.log('res:'+res);但控制台显示结果为res:[objectObject],并非想要查看的数据。最基本的要求是先去掉+号,试试看问题原因1......
  • 宝塔搬家后打开网站为何出现:No input file specified.
    当你在使用宝塔面板搬家后出现“Noinputfilespecified.”的错误,这通常是由于PHP解析器找不到正确的入口文件导致的。这种情况可能与 .user.ini 文件有关,尤其是当你打包网站源码时包含了根目录下的 .user.ini 文件。解决方案1.检查 .user.ini 文件删除 .user.in......
  • Js中获取鼠标中的某一个点的位置以及getBoundingClientRect
    getBoundingClientRect() 是一个用于获取元素位置和尺寸信息的方法。它返回一个DOMRect对象,其提供了元素的大小及其相对于视口的位置,其中包含了以下属性: x:元素左边界相对于视口的x坐标。y:元素上边界相对于视口的y坐标。width:元素的宽度。height:元素的高度。top:元素......
  • Qt C++设计模式->组合模式
    组合模式(CompositePattern)是一种结构型设计模式,允许你将对象组合成树形结构以表示部分与整体的层次关系。组合模式使得客户端可以以统一的方式对待单个对象和组合对象,简化了对复杂树形结构的操作。组合模式的应用场景组合模式非常适合用于需要处理树形结构的场景,比如文件系......
  • C#静态导入
    在C#中,静态导入通常指的是使用usingstatic指令,它允许你直接访问静态类中的静态成员,而不需要每次都写出类名。这在处理静态方法、属性或常量时非常有用,可以使代码更简洁。使用方法引入命名空间中的静态类:使用usingstatic语法可以导入特定静态类。直接访问静态成员:引入......
  • C#在国外真的很流行吗?这份报告,告诉你答案。
    大家好,我是编程乐趣。在某乎一直都有人在问类似问题:为什么差距那么大,C#在国外真的很流行吗?刚好全球最大的开发者问答论坛StackOverflow刚刚发布了2024年开发者调研报告,这份报告就有调查各种编程语言的使用流行程度,可以很好地解答这个问题。下面我们一起来看看吧。此次......