Base64与File之间的相互转化

  //文件转base64文件流
 public AttachmentModel ReadDocument(T_BAFJ modelItem) 
        {
            AttachmentModel attachment = new AttachmentModel();
            if (modelItem!=null) {              
                string fileFullPath = Path.Combine(UploadRoot, modelItem.F_WJLJ);//保存文件的全路径             
                using (FileStream filestream = new FileStream($"{fileFullPath}", FileMode.OpenOrCreate, FileAccess.Read))
                {
                    byte[] bt = new byte[filestream.Length];
                    //用来限定每次的读取字节数,也可以byte[] b=new byte[Fsread.Length];             
                    while (true)
                    {
                        int r = filestream.Read(bt, 0, bt.Length);
                        if (r == 0)
                            break;
                    }
                    attachment.Wjlx = modelItem.F_WJLX;
                    attachment.Wjmc = modelItem.F_WJMC;
                    attachment.AttachmentContent = Convert.ToBase64String(bt);
                    //base64StringToPdf(attachment.AttachmentContent, $@"D:\gitProject\规章库\regulationlibrary\guizhangku\Bdyh.bjrd.web\T_BBXM\{modelItem.F_WJMC}");

                }
            }      
            return attachment;
        }
         //文件流转文件
        public void base64StringToPdf(String base64Content, String filePath)
        {
            try
            {        
//注意:文件直接转base64前面会带有“data:application/pdf;base64,”前缀,需要去掉。 base64Content = base64Content.Replace("data:application/pdf;filename=generated.pdf;base64,", string.Empty); string base64ContentData = base64Content.Trim().Replace("%", "").Replace(",", "").Replace(" ", "+"); if (base64ContentData.Length % 4 > 0) { base64ContentData = base64ContentData.PadRight(base64ContentData.Length + 4 - base64ContentData.Length % 4, '='); } byte[] bytes = Convert.FromBase64String(base64ContentData); string location = filePath; System.IO.FileStream stream = new FileStream(location, FileMode.CreateNew); System.IO.BinaryWriter writer = new BinaryWriter(stream); writer.Write(bytes, 0, bytes.Length); writer.Close(); } catch (Exception ex) { //LogHelper.WriteLog(GetType(), "base64StringToPdf异常错误为:" + ex.Message); } }

 

posted @ 2023-03-10 14:14  哈根达斯  阅读(344)  评论(0编辑  收藏  举报