首页 > 解决方案 > 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?

标签: delphihttp-post

解决方案


这个问题在 Delphi 10.3 中得到解决,其中扩展了接口,可以直接使用流。


推荐阅读