简体   繁体   English

Delphi:如何将TIdBytes编码为Base64字符串?

[英]Delphi: How to encode TIdBytes to Base64 string?

How to encode TIdBytes to Base64 string (not AnsiString) ? 如何将TIdBytes编码为Base64字符串(不是AnsiString)?

  ASocket.IOHandler.CheckForDataOnSource(5);

  if not ASocket.Socket.InputBufferIsEmpty then
  begin
    ASocket.Socket.InputBuffer.ExtractToBytes(data);
    // here I need to encode data to base64 string, how ? I don't need AnsiString!!
    // var s:string;
    s := EncodeBase64(data, Length(data)); // but it will be AnsiString :(

Or how to send AnsiString via AContext.Connection.Socket.Write() ? 或者如何通过AContext.Connection.Socket.Write()发送AnsiString?

Compiler saying Implicit string cast from 'AnsiString' to 'string' 编译器说从'AnsiString'到'string'的隐式字符串转换

"data" variable contains UTF-8 data from website. “data”变量包含来自网站的UTF-8数据。

You can use Indy's TIdEncoderMIME class to encode String , TStream , and TIdByte data to base64 (and TIdDecoderMIME to decode from base64 back to String , TStream , or TIdBytes ), eg: 您可以使用Indy的TIdEncoderMIME类将StringTStreamTIdByte数据编码为base64(以及TIdDecoderMIME以从base64解码回StringTStreamTIdBytes ),例如:

s := TIdEncoderMIME.EncodeBytes(data);

As for sending AnsiString data, Indy in D2009+ simply does not have any TIdIOHandler.Write() overloads for handling AnsiString data at all, only UnicodeString data. 至于发送AnsiString数据,D2009 +中的Indy根本没有任何TIdIOHandler.Write()重载来处理AnsiString数据,只有UnicodeString数据。 To send an AnsiString as-is, you can either: 要按原样发送AnsiString ,您可以:

1) copy the AnsiString into a TIdBytes using RawToBytes() and then call TIdIOHandler.Write(TIdBytes) : 1)使用RawToBytes()AnsiString复制到TIdBytes ,然后调用TIdIOHandler.Write(TIdBytes)

var
  as: AnsiString;
begin
  as := ...;
  AContext.Connection.IOHandler.Write(RawToBytes(as[1], Length(as)));
end;

2) copy the AnsiString data into a TStream and then call TIdIOHandler.Write(TStream) : 2)将AnsiString数据复制到TStream ,然后调用TIdIOHandler.Write(TStream)

var
  as: AnsiString;
  strm: TStream;
begin
  strm := TMemoryStream.Create;
  try
    strm.WriteBuffer(as[1], Length(as));
    AContext.Connection.IOHandler.Write(strm);
  finally
    strm.Free;
  end;
end;

Or: 要么:

var
  as: AnsiString;
  strm: TStream;
begin
  as := ...;
  strm := TIdMemoryBufferStream.Create(as[1], Length(as));
  try
    AContext.Connection.IOHandler.Write(strm);
  finally
    strm.Free;
  end;
end;

In later versions of Delphi with Unicode string as the default...you should be safe to simply cast the return value as a String to rid yourself of that warning. 在Delphi的更高版本中,默认情况下使用Unicode字符串...您应该可以安全地将返回值强制转换为字符串以消除该警告。 Base64 only returns a small set of values (ascii) ... which will never lead to data loss in conversion to Unicode. Base64只返回一小组值(ascii)...在转换为Unicode时永远不会导致数据丢失。

s := String(EncodeBase64(data, Length(data))); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM