Get files from TWebRequest in Delphi

I'm using Delphi as a server to serve a number of different requests. All that are simple strings works fine, but I have some trouble recieving files.

All are implemented using a Webbroker service, so I get a method

WebModule1WebActionItem1Action(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);

I have a /test method, with type=mtPost.

Inside of the action, I do the following:

MimeType   := Request.ContentFields.Values['MimeType'];
  for i := 0 to Request.Files.Count-1 do begin
    // never entered
    aFile := Request.Files.Items[i];
    ms := TMemoryStream.Create;
    aFile.Stream.Position := 0;
    ms.CopyFrom(aFile.Stream, aFile.Stream.Size);

Apparently whatever I send is never recognized as files, but I dont know why. The HTML used to post, looks like this:

<form id="myForm" action="http://localhost:8080/test" method="post" enctype="multipart/form-data">
     <input type="file" size="60" name="myfile">
     <input type="text" size="10" name="mimetype" value="image/hest">
     <input type="submit" value="upload">

I'd appriciate anybody telling me what could be wrong - and how to solve it. Basically I just need to be able to recieve 1 file at the time, including the mimetype (because I need to return it when I serve the file later)


You could simply just read the raw request and split on the first double line break:

Data := Request.ReadUnicodeString(Request.ContentLength);
// Where StrAfter is a function that splits on the first occurrence
// of the first parameter.
Data := Trim(StrAfter(#13#10#13#10, Data));

Of course, that only allows you to read one file. Maybe you should read the headers to see the exact length of each file to split Data between them.

I had the same problem and it took quite awhile to find the answer. TWebRequest does not process Multipart forms by default. Include the unit ReqMulti in your project and it will be extended to support multipart and suddenly the Request.Files object will actually have data in it.

As a side note, once you're using multipart forms Request.GetFieldByName doesn't seem to work anymore but Request.ContentFields.Values['fieldname'] does.

Need Your Help

Avoiding focus change when selecting range -- Excel

excel vba

I have a macro which creates a sub range from one given, depending on some criteria.

.NET Regular Expression for Regular Expression Parsing

c# .net regex

I want to return matches from a regular expression string. The regex string is: