delphi - Adding an "AddStream" method to TMultipartFormData for use with TNetHTTPClient.Post
问题描述
Using Delphi 10.2.3,
I want to upload an image from a TStream to a web server using TNetHTTPClient.Post and TMultipartFormData.
My problem is that the TMultipartFormData class does not have an 'AddStream' function (I'm assuming it needs a file name to generate the mime type), so I decided to add my own since I know the mime types (and a valid file name) in advance.
I never used class inheritance or class helpers in Delphi 10.2.3 and after reading and trying it out I've reached a point where I'm obviously missing something but can't figure out what.
I tried:
Type
TMultipartFormDataStream = class (TMultipartFormData)
procedure AddStream(AStream : TStream; const AFieldName, AFilePath: string);
end;
procedure TMultipartFormDataStream.AddStream(AStream : TStream; const AFieldName, AFilePath: string);
var
LType: string;
begin
AdjustLastBoundary;
WriteStringLn('--' + FBoundary);
WriteStringLn(sContentDisposition + ': form-data; name="' + AFieldName + '"; filename="' + ExtractFileName(AFilePath) + '"'); // do not localize
LType := GetFileMIMEType(AFilePath);
WriteStringLn(sContentType + ': ' + LType + #13#10); // We need 2 line break here // do not localize
try
FStream.CopyFrom(AStream, 0);
finally
end;
WriteStringLn('');
end;
However, none of the inherited's class private functions are accessible.
I also tried using a class helper instead of directly inheriting, but again the private functions are not accessible and I would rather not use an RTTI hack.
What is the best solution/work-around to upload the image from a stream using TNetHTTPClient? Do I really have to save the stream to a file just to add it to the multipart form data?
解决方案
这个问题在 Delphi 10.3 中得到解决,其中扩展了接口,可以直接使用流。
推荐阅读
- android - 在我的情况下,如何从 api 获取准确的数据?
- node.js - 在 SSR 上的反应组件中导入 scss
- css - CSS flexbox:可变高度内容区域下方的可变高度页脚
- elasticsearch - Elasticsearch 通过几个不同权重的 geo_points 过滤
- regex-group - 如何创建可选的命名组?
- rust - 用serde反序列化成不同的特征实现者?
- android - 如何在干净的架构中实现购物车?
- eslint - 无法关闭 eslint no-unused-expressions
- python - Matplotlib - 为什么图形会被保存两次?
- localization - 嵌入式脚本语言的编译时本地化