Dave Gill
Dave Gill

Reputation: 244

Delphi XE6 Image Upload from Mobile to Server

I am attempting to build an app that would allow the user to post their image from their mobile device to the web server. I have been trying to do this for a couple of days and have not found a way of doing it using XE6...Does anybody have a clue?

I have tried using the RestClient library but I can not find a way of attaching an image to a Parameter on a rest request. My latest attempt is:-

var
  mStream : TMemoryStream;
  fileData : TJSONArray;
begin
  mStream  := TMemoryStream.Create();
  image1.Bitmap.SaveToStream(mStream);
  fileData := TDBXJSONTools.StreamToJSON(mStream, 0, mStream.Size);
  restRequest1.Params.ParameterByName('file').Value := fileData.Value;
  restRequest1.Execute;
  mStream.Free;
end;

Nothing comes through in the file parameter on the server side.

I have also tried using the MultiPartFormDataStream on the IdHttp component but the AddFile method expect a filename... Because I am taking the image from the Camera I do not have a filename so that stumped me also. And I could not find a way of attaching a stream to one of the params on that either.

I also tried to use the IDHTTP to post a stream directly to the server, which is a PHP server but the request did not contain any data other than the normal HTTP headers.

Thanks in advance for any help.

Upvotes: 1

Views: 2332

Answers (1)

JRL
JRL

Reputation: 3401

To upload a stream as a HTML form field with Indy you need to use TIdMultiPartFormDataStream. AddFormField.

You can also pass other fields as well.

uses IdHTTP, IdMultipartFormData;

var
  http: TIdHttp;
  multiStream: TIdMultiPartFormDataStream;
begin
  multiStream := TIdMultiPartFormDataStream.Create;
  try
    multiStream.AddFormField('field1', 'image/jpeg', '', sourceStream, 'image1.jpg');
    multiStream.AddFormField('field2', 'value2');

    http := TIdHttp.Create(nil);
    try
      http.Post(url, multiStream);
    finally
      http.Free;
    end;
  finally
    multiStream.Free;
  end;
end;

The file name parameter is optional and will be stored in PHP's $_FILES['field1']['name'].

Upvotes: 3

Related Questions