TidHttpServer - uploading file fom web browser

799 views
Skip to first unread message

Joe Aley

unread,
Jan 14, 2006, 11:52:42 PM1/14/06
to
Hi all...

I could receive a file from a web browser but it's not exactly the same
i send. Seems there was an encode.
Here goes the form i used:

<form enctype="multipart/form-data" action="upload" method="post">
<input type="file" name="upfile">
<input type="submit" value="Send">
</form>

now goes the OnCommandGet() code:
//-----------
TheFile:=TMemoryStream.Create;
TheFile.LoadFromStream(ARequestInfo.PostStream);
TheFile.SaveToFile('uploaded.dat');
//-----------
Another thing i did was add this line in ServerCreatePostStream event
//-----------
procedure TForm1.ServerCreatePostStream(ASender: TIdPeerThread;
var VPostStream: TStream);
begin
VPostStream:=TMemoryStream.Create;
end;
//------------

Now, what do i have to do to decode it?

Remy Lebeau (TeamB)

unread,
Jan 17, 2006, 4:32:11 PM1/17/06
to

"Joe Aley" <joeal...@yahoo.com> wrote in message
news:43c9d287$1...@newsgroups.borland.com...

> <form enctype="multipart/form-data" action="upload" method="post">

You can use TIdMessageDecoderMIME to manually parse "multipart/form-data"
submissions. For example:

uses IdMessageDecoderMIME, IdMessage;

procedure TForm1.IdHTTPServer1CreatePostStream(AThread: TIdPeerThread;


var VPostStream: TStream);
begin
VPostStream := TMemoryStream.Create;
end;

procedure TForm1.IdHTTPServer1CommandGet(AThread: TIdPeerThread;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
var
S: String;

procedure DecodeFormData(const Header: String; ASourceStream:
TStream);
var
MsgEnd: Boolean;
Decoder: TIdMessageDecoder;
Tmp: String;
Dest: TStream;
begin
MsgEnd := False;
Decoder := TIdMessageDecoderMIME.Create(nil);
try
TIdMessageDecoderMIME(Decoder).MIMEBoundary :=
TIdMIMEBoundary.FindBoundary(Header);
Decoder.SourceStream := ASourceStream;
Decoder.FreeSourceStream := False;
Decoder.ReadLn;
repeat
Decoder.ReadHeader;
case Decoder.PartType of
mcptUnknown:
raise Exception('Unknown form data detected');
mcptText:
begin
Tmp :=
Decoder.Headers.Values['Content-Type'];
Dest := TMemoryStream.Create;
try
Decoder := Decoder.ReadBody(Dest,
MsgEnd);
if AnsiSameText(Fetch(Tmp, ';'),
'multipart/mixed') then
DecodeFormData(Tmp, Dest)
else
// use Dest as needed...
finally
FreeAndNil(Dest);
end;
end;
mcptAttachment:
begin
Tmp := ExtractFileName(Decoder.FileName);
if Tmp <> '' then
Tmp := 'c:\some folder\" + Tmp
else
Tmp := MakeTempFilename("c:\some
folder\");
Dest := TFileStream.Create(Tmp, fmCreate);
try
Decoder = Decoder.ReadBody(Dest,
MsgEnd);
finally
FreeAndNil(Dest);
end;
end;
end;
until (Decoder = nil) or MsgEnd;
finally
FreeAndNil(Decoder);
end;
end;

begin
S := ARequestInfo.Headers.Values['Content-Type'];
if AnsiSameText(Fetch(S, ';'), 'multipart/form-data') then
DecodeFormData(S, ARequestInfo.PostStream)
else
// use request data as needed...
end;


Gambit


Reply all
Reply to author
Forward
0 new messages