Delphi used: 2007.
Hello,
I have a simple web page with two text input and one file input. Now, for the form to be sent, both the text inputs and the file input have to be filled. With Synapse, I know how to upload a file (HttpPostFile) and how to post data (HttpMethod). However, I don't know how to do both.
After looking at the source code of Synapse, I guess I have to "format" my data with boundaries or something like that. I guess I should have one boundary for my input file and another boundary for my text inputs. I found an article on the subject, but it's about sending email attachments. I tried to reproduce what they said with Synapse, with no results.
Code for HttpPostFile:
function HttpPostFile(const URL, FieldName, FileName: string;
const Data: TStream; const ResultData: TStrings): Boolean;
var
HTTP: THTTPSend;
Bound, s: string;
begin
Bound := IntToHex(Random(MaxInt), 8) + '_Synapse_boundary';
HTTP := THTTPSend.Create;
try
s := '--' + Bound + CRLF;
s := s + 'content-disposition: form-data; name="' + FieldName + '";';
s := s + ' filename="' + FileName +'"' + CRLF;
s := s + 'Content-Type: Application/octet-string' + CRLF + CRLF;
WriteStrToStream(HTTP.Document, s);
HTTP.Document.CopyFrom(Data, 0);
s := CRLF + '--' + Bound + '--' + CRLF;
WriteStrToStream(HTTP.Document, s);
HTTP.MimeType := 'multipart/form-data; boundary=' + Bound;
Result := HTTP.HTTPMethod('POST', URL);
if Result then
ResultData.LoadFromStream(HTTP.Document);
finally
HTTP.Free;
end;
end;
Thank you.
Good reading: http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2
Problem solved. I keep the question public in case anyone has the same question one day.
I also use synapse in my projects. To be make my work simple and faster with Synapse, I wrote THTTPSendEx class, that gives fast speed of using and minimum of code and more features. Currently it's a beta version.
It's views like Indy.
Create THTTPSendEx class. Create methods OnBeginWork, OnWork, OnWorkEnd from it prototypes(see pas file), and assign it to created class. Thats all what you need, and just call GET, POST functions of the class.
I also implement multipart-fomdata for fast file posting in this format as TMultipartFormDataStream class. With it you can easy write files and fields.
Example of using:
You can see it at my web-site.
If you have any ideas for this, please write it's as a comment to project page.
Sorry for mistakes in english.
Your code is close. You are only sending your file field but not your text fields. To do all three, try this instead:
If you switch to Indy, you can use its
TIdMultipartFormDataStream
class: