Embarcadero RAD Studio XE

Upload a BMP file

Server端ServerMethodsUnit1

unit ServerMethodsUnit1;

interface

uses System.SysUtils, System.Classes, Datasnap.DSServer, Datasnap.DSAuth,
     JSON, DBXJSONCommon, Vcl.Graphics,  Vcl.Imaging.jpeg, Vcl.Imaging.pngimage;

type
{$METHODINFO ON}
  TServerMethods1 = class(TComponent)
  private
    { Private declarations }
  public
    { Public declarations }
    function uploadPicture(jsa: TJSONArray): string;
  end;
{$METHODINFO OFF}

implementation


uses System.StrUtils;

function TServerMethods1.uploadPicture(jsa: TJSONArray): string;
var
  ms : TStream;
  wic : TWICImage;
  fileName,   fileNameExt : string;

begin

  fileName := 'c:\temp\A.';
  ms := TMemoryStream.Create;
  ms.Position := 0;
  ms := TDBXJSONTools.JSONToStream(jsa);

  wic := TWICImage.Create;
  wic.LoadFromStream(ms);

  if (wic.ImageFormat = wifBmp) then fileNameExt := 'bmp'
  else if (wic.ImageFormat = wifJpeg ) then fileNameExt := 'jpeg'
  else if (wic.ImageFormat = wifPng) then fileNameExt := 'png'  ;

  wic.SaveToFile(fileName+fileNameExt);

  wic.Free;
  ms.Free;

  Result := 'The picture is saved.';
end;
end.

Client端clientMain

unit ClientMain;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtDlgs, Vcl.extCtrls, Vcl.StdCtrls, JSON, DBXJSONCommon,
  Vcl.Imaging.pngimage, Vcl.Imaging.jpeg;

type
  TForm1 = class(TForm)
    OpenPictureDialog1: TOpenPictureDialog;
    Button1: TButton;
    Image1: TImage;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

uses ClientModuleUnit1;

procedure TForm1.Button1Click(Sender: TObject);
begin
    { Execute an open picture dialog. }
  if OpenPictureDialog1.Execute then
    { First check if the file exists. }
    if FileExists(OpenPictureDialog1.FileName) then
      { If it exists, load the data into the image component. }
      Image1.Picture.LoadFromFile(OpenPictureDialog1.FileName)
    else
      { Otherwise raise an exception. }
      raise Exception.Create('File does not exist.');
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  ms: TStream;
  jsa: TJSONArray;
  picType : integer;
begin

  ms := TMemoryStream.Create;
  Image1.Picture.Graphic.SaveToStream(ms);
  ms.Position := 0;
  jsa := TJSONArray.Create;
  jsa := TDBXJSONTools.StreamToJSON(ms, 0, ms.Size) ;

  showMessage(ClientModule1.ServerMethods1Client.uploadPicture(jsa));
  ms.Free;
  jsa.Free;

end;

end.