1

The code below works fine if executed as a single command. I use it to download PDFs that are typically a few megabytes in size.

However, when I execute it multiple times in a loop, all the downloaded files are exactly the same size (truncated @ ~50KB). Is there an issue with my code or is this the server not being able to deliver as expected?

type
  TKeyValuePair = record  
    Key:   String;
    Value: String;
  end;
  TKeyValueSet = Array of TKeyValuePair;

// ...

function TDM.MultipartPost(const URL, LocalFile: String; const MultipartData: TKeyValueSet): Boolean;
var
  i:          Integer;
  httpclient: THTTPClient;
  formdata:   TMultipartFormData;
  fstream:    TFileStream;

begin
  httpclient := THTTPClient.Create;
  formdata   := TMultipartFormData.Create();
  fstream    := nil;
  try
    fstream := TFileStream.Create(LocalFile, fmCreate);
  except
    // removed
  end;
  try
    for i := Low(MultipartData) to High(MultipartData) do
      formdata.AddField(MultipartData[i].Key, MultipartData[i].Value);
    try
      httpclient.Post(url, formdata, fstream);
    except
      // removed
    end;
  finally
    FlushFileBuffers(fstream.Handle);
    fstream.Free;
    formdata.Free;
    httpclient.Free;
    //
    Result := FileExists(LocalFile) and (GetFileSize(LocalFile) > 0); 
  end;
end;
Olivier
  • 13,283
  • 1
  • 8
  • 24
tua
  • 33
  • 4
  • Hard to tell what's happening. When you do a loop, the first iteration should have the exact same effect as when you execute a single command, so at least the first download should be successful. – Olivier Aug 04 '21 at 14:06
  • Please show the code that is performing the loop. Also, I would not recommend setting the `Result` of `MultipartPost()` based on the file's existence, but rather on whether or not any exceptions are raised. – Remy Lebeau Aug 04 '21 at 14:33

1 Answers1

0

Mea culpa - my apologies to all that read/replied to my post. I just built a minimal, but complete application to demonstrate the issue and, voila, it worked just fine.

1 hour or so of not seeing the forest for all the trees later:

I accidentally used an incorrect URL to post to :(

tua
  • 33
  • 4