Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi SOAP: delete temporary file after response dispatched

Tags:

soap

delphi

I have a soap method that on the fly creates and respond with a PDF content.

On method finally, the temporary pdf file It is deleted.

It is finally the right place for perform this operation?

procedure TWbModule.WbModuleGetPDFAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
var
    aPDFFileTemp : string;
begin
    try
        // getTempPdf() creates and returns the PDF path, eg.: C:\files\foo.pdf
        aPDFFileTemp := getTempPdf();

        // set response content stream with file stream
        Response.ContentStream := TFileStream.Create(aPDFFileTemp, fmOpenRead or fmShareDenyNone);
        Response.ContentType   := 'application/pdf';
    finally
        // delete temporary file
        // It is the right place for perform this operation?
        if FileExists(aPDFFileTemp) then DeleteFile(aPDFFileTemp );
    end;
end;
like image 487
ar099968 Avatar asked Feb 09 '23 17:02

ar099968


1 Answers

If you only want to have a temporary file then you should create it as a temporary file.

This class creates a stream with a temporary and self destructing file.

uses
  System.Classes;

type
  TTempFileStream = class( THandleStream )
  public
    constructor Create( );
    destructor Destroy; override;
  end;

implementation

uses
  System.IOUtils,
  System.SysUtils,
  Winapi.Windows;

{ TTempFileStream }

constructor TTempFileStream.Create;
var
  fileName  : string;
  fileHandle: THandle;
begin
  fileName := TPath.GetTempFileName( );

  fileHandle := CreateFile(
    PChar( fileName ),
    GENERIC_ALL,
    0,
    nil,
    CREATE_ALWAYS,
    FILE_ATTRIBUTE_TEMPORARY or FILE_FLAG_DELETE_ON_CLOSE,
    0 );
  if fileHandle = INVALID_HANDLE_VALUE
  then
    RaiseLastOSError( GetLastError, sLineBreak + fileName );
  inherited Create( fileHandle );
end;

destructor TTempFileStream.Destroy;
begin
  CloseHandle( Handle );
  inherited;
end;

The best option would be to write the data (PDF content) into this TTempFileStream and return the instance from getTempPdf()

function getTempPdf() : TStream;
begin
  Result := TTempFileStream.Create;
  // create the PDF document and write into the result stream
end;

procedure TWbModule.WbModuleGetPDFAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
begin
  Response.ContentStream := getTempPdf();
  Response.ContentType   := 'application/pdf';
end;

When the response is sent the stream will be freed and the file will be deleted.

like image 90
Sir Rufo Avatar answered Apr 28 '23 13:04

Sir Rufo