【发布时间】:2019-08-05 17:22:46
【问题描述】:
我正在使用 delphi 中的以下代码 sn-p 将图像编码为 Base64。
procedure TWM.WMactArquivosAction(Sender: TObject; Request: TWebRequest;
Response: TWebResponse; var Handled: Boolean);
var
ImagePath: string;
JsonObject: TJSONObject;
inStream, outStream: TStream;
StrList: TStringList;
begin
inStream := TFileStream.Create(ImagePath, fmOpenRead);
try
outStream := TFileStream.Create('final_file', fmCreate);
JsonObject := TJSONObject.Create;
try
TNetEncoding.Base64.Encode(inStream, outStream);
outStream.Position := 0;
StrList := TStringList.Create;
StrList.LoadFromStream(outStream);
JsonObject.AddPair('file', StrList.Text);
finally
Response.Content := JsonObject.ToString;
outStream.Free;
JsonObject.DisposeOf;
end;
finally
inStream.Free;
end;
end;
工作正常,文件转换为Base64 并添加到JsonObject。
问题是,当从网络服务器检索此 JsonObject 时,我得到了一个错误的 json 格式,因为 base64 字符串中有换行符。
你可以看到红色的是字符串。第一个换行后,json被打乱,显示为蓝色,表示json响应有错误。
问题
所以,问题在于,当编码为Base64 时,它会在字符串中添加换行符,而Json 不支持这一点。
我的猜测
我有一个猜测,确实有效,但我不确定这是最好的解决方案。
我遍历了TStringList 中的所有Strings,并将数据添加到TStringBuilder 中。毕竟,我在Json 中添加了TStringBuilder。看看我的代码。
...
var
...
StrBuilder: TStringBuilder;
begin
...
try
...
StrList.LoadFromStream(outStream);
// New
StrBuilder := TStringBuilder.Create;
for I := 0 to StrList.Count - 1 do
StrBuilder.Append(StrList.Strings[I]);
JsonObject.AddPair('file', StrBuilder.ToString);
finally
Response.Content := JsonObject.ToString;
...
end;
...
end;
如您所见,JSON 现在很好。
问题
- 循环遍历所有项目对我来说似乎是一个不好的解决方案,它可以正常工作吗? (它在 localhost 上 344 毫秒内得到响应)
- 有更好的解决方案吗?
【问题讨论】: