multipart/form-data
In this tutorial and the project we build here, we'll use the server mentioned in the tutorial above as our test server. It's a good test that shows that the protocol used by the Indy built client application matches that of a regular browser. A kind of confirmation if you will.
To assist us in this task, I've built a simple class derived from a TMemoryStream that encapsulates the nitty-gritty of the multipart/form-data encoding protocol.
TMemoryStream
TMsMultipartFormDataStream
TMsMultiPartFormDataStream = class(TMemoryStream) private FBoundary: string; FRequestContentType: string; function GenerateUniqueBoundary: string; public procedure AddFormField(const FieldName, FieldValue: string); procedure AddFile(const FieldName, FileName, ContentType: string; FileData: TStream); overload; procedure AddFile(const FieldName, FileName, ContentType: string); overload; procedure PrepareStreamForDispatch; constructor Create; property Boundary: string read FBoundary; property RequestContentType: string read FRequestContentType; end;
This class allows for uploading multiple files along with multiple form fields. As you can see, the interface is very simple to understand and use. So I won't go into the details of each of them.
added
PrepareStreamForDispatch
http://www.matlus.com/scripts/multifileupload.dll/upload
action
AURL
IdHTTP
Send
OnClick
procedure TForm1.Button2Click(Sender: TObject); var ResponseStream: TMemoryStream; MultiPartFormDataStream: TMsMultiPartFormDataStream; begin MultiPartFormDataStream := TMsMultiPartFormDataStream.Create; ResponseStream := TMemoryStream.Create; try IdHttp1.Request.ContentType := MultiPartFormDataStream.RequestContentType; MultiPartFormDataStream.AddFormField('PersonName', edtPersonName.Text); MultiPartFormDataStream.AddFormField('Description', edtDescription.Text); MultiPartFormDataStream.AddFile(edtFile.Name, edtFile.Text, edtMIMEType.Text); { You must make sure you call this method *before* sending the stream } MultiPartFormDataStream.PrepareStreamForDispatch; MultiPartFormDataStream.Position := 0; IdHTTP1.Post(edtHost.Text, MultiPartFormDataStream, ResponseStream); finally MultiPartFormDataStream.Free; ResponseStream.Free; end; end;
http://www.matlus.com/scripts/multifileupload.dll/upload/filename