You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#与Delphi生成Base64字符串差异及REST API传输PDF方案

问题描述

我使用Delphi 10.3搭建了REST服务器,该服务接收3个参数,其中一个为存储PDF文件Base64字符串的参数。

当我使用以下Delphi代码生成Base64字符串时:

function  ConvertPdfFileToBase64D(PdfFileName : String; var Base64Str : String) : Boolean;
var
  success   : Boolean;
  b64       : String;
  fBytes    : TBytes;
  fSize     : Integer;

  function FileToBytes(const AFileName: string; var Bytes: TBytes): Boolean;
  var
    Stream: TFileStream;
  begin
    if not FileExists(AFileName) then
    begin
      Result := False;
      Exit;
    end;
    Stream := TFileStream.Create(AFileName, fmOpenRead);
    try
      fSize := Stream.Size;
      SetLength(Bytes, fSize);
      Stream.ReadBuffer(Pointer(Bytes)^, fSize);
    finally
      Stream.Free;
    end;
    Result := True;
  end;
begin
  Result := False;
  Base64Str := '';
  if FileToBytes(PdfFileName,fBytes) then
  begin
    //Base64Str := TNetEncoding.Base64.EncodeBytesToString(fBytes, fSize);
    Base64Str := TNetEncoding.Base64.EncodeBytesToString(fBytes);
    Result := True;
  End;
end;

在Delphi REST API中接收该Base64字符串后,我可以成功解码并保存为PDF文件。

但当我使用Visual Studio C#通过以下代码生成Base64字符串并发送时:

Byte[] fileBytes = File.ReadAllBytes(@"textBox1.Text");
var content = Convert.ToBase64String(fileBytes);

得到的Base64字符串与Delphi生成的不同,无法正常处理。请问如何正确从C#向Delphi REST API发送PDF文件的Base64字符串?


解决方案

1. 修复C#文件读取的路径错误

你的C#代码存在明显路径错误:@"textBox1.Text"是将字符串字面量作为文件名,而非读取文本框中输入的文件路径。修正代码如下:

string filePath = textBox1.Text;
if (File.Exists(filePath))
{
    Byte[] fileBytes = File.ReadAllBytes(filePath);
    var content = Convert.ToBase64String(fileBytes);
    // 此处将content作为参数发送到Delphi REST API
}

2. 统一Base64格式

Delphi的TNetEncoding.Base64默认生成带换行符的Base64字符串(每76个字符换行),而C#的Convert.ToBase64String默认生成无换行的Base64,格式差异会导致解码失败,可通过以下两种方式统一:

方式一:让C#生成带换行的Base64

使用Base64FormattingOptions.InsertLineBreaks参数生成与Delphi格式一致的Base64:

var content = Convert.ToBase64String(fileBytes, Base64FormattingOptions.InsertLineBreaks);

方式二:让Delphi解码时忽略换行符

在Delphi的解码逻辑中先移除所有换行符,再执行解码:

// 假设接收的Base64字符串为ReceivedBase64Str
ReceivedBase64Str := StringReplace(ReceivedBase64Str, #13#10, '', [rfReplaceAll]);
ReceivedBase64Str := StringReplace(ReceivedBase64Str, #10, '', [rfReplaceAll]);
// 再执行解码操作

3. 确保HTTP参数传递不被破坏

发送请求时,若将Base64字符串作为URL参数传递,需先进行URL编码避免特殊字符被转义;若使用FormData或JSON请求体传递,直接发送字符串即可:

// URL编码示例(适用于URL参数场景)
string encodedContent = System.Web.HttpUtility.UrlEncode(content);
// 或使用System.Net.WebUtility.UrlEncode(适用于.NET Core/.NET 5+)

内容的提问来源于stack exchange,提问作者mazluta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 20:17:26