bob_saginowski
bob_saginowski

Reputation: 1429

Delphi upload image HTTP server

In my VCL application I have an http server. I am trying to upload an image from a browser. Here is the code of the commandGet procedure:

procedure TForm6.HTTPServerCommandGet(AContext: TIdContext;
  ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
var
  imageStream: TMemoryStream;
begin
  if Pos('command=addImage', ARequestInfo.UnparsedParams) > 0 then
  begin
    AResponseInfo.ContentText := UploadImageForm;
  end
  else if Pos('command=saveImage', ARequestInfo.UnparsedParams) > 0 then
  begin
    imageStream := TMemoryStream.Create;

    try
      ARequestInfo.PostStream.Seek(0, soFromBeginning);
      imageStream.LoadFromStream(ARequestInfo.PostStream);
      imageStream.SaveToFile('picture.jpeg');
    finally
      imageStream.Free;
    end;
  end;
end;

Here is the code of UploadImageForm:

 function UploadImageForm: string;
 var
   uploadImageHTMLForm: TStringBuilder;
 begin
   uploadImageHTMLForm := TStringBuilder.Create;

   try
     // by default enctype is application/x-www-form-urlencoded
     // uploadImageHTMLForm.AppendLine('<form action="/?command=saveImage" method="post">');
     // EDIT
     uploadImageHTMLForm.AppendLine('<form action="/?command=saveImage" method="post" enctype="multipart/form-data">');
     uploadImageHTMLForm.AppendLine('<input type="file" name="uploadField">');
     uploadImageHTMLForm.AppendLine('<input type="submit">');
     uploadImageHTMLForm.AppendLine('</form>');
     Result := uploadImageHTMLForm.ToString;
   finally
     uploadImageHTMLForm.Free;
   end;
 end;

The problem is that when I select a .jpeg file and click submit ARequestInfo.PostStream is empty (I create it onCreatePostStream). Any idea how to solve it.

Upvotes: 1

Views: 3169

Answers (1)

mjn
mjn

Reputation: 36654

HTML form <input> elements with type=file should use enctype="multipart/form-data" (see https://stackoverflow.com/a/2436725/80901).

However, multipart/form-data is not supported by TIdHTTPServer - see TIdHTTPServer file upload

Additional code is required to extract the file content from the request body. (There have been examples of that posted in the Embarcadero and Indy forums before.)

Upvotes: 2

Related Questions