unit htmlinputfile;

interface

uses SysUtils, System.Web.UI, System.Web.UI.HtmlControls, System.Web.UI.WebControls;

type THtmlInputFile = Class(System.Web.UI.HtmlControls.HtmlInputFile)
	private
		fErrorMSG:string;
	
		fServerFolder:string;
		fImageFolder:string;
		
		function GetUniqueFileName(fileName:string):string;

	public
		constructor Create; 
		function UploadFile(var ImageNameOnServer:string):boolean;
	published
		property ErrorMSG : string read fErrorMSG write fErrorMSG;
		property ImageFolder : string read fImageFolder write fImageFolder;
		// or ServerFolder := Request.ApplicationPath + ImageFolder
		property ServerFolder : string read fServerFolder write fServerFolder;
end;

implementation

function THtmlInputFile.GetUniqueFileName(fileName:string):string;
begin
	while FileExists(ServerFolder + fileName) do
		fileName:='_' + fileName;
		
	Result:=fileName;
end;

function THtmlInputFile.UploadFile(var ImageNameOnServer:string):boolean;
//returns true if saved successfully
//ImageNameOnServer like "imagefolder/imenaclientu_datetimestamp"
var
	strFileName : string;
	sToFileName : string;
begin
	Result:=true;
	if (Assigned(PostedFile)) then
	begin    
  	strFileName := ExtractFileName(PostedFile.FileName);
		if strFileName = '' then
		begin
			Result:=true;
			Exit;
		end; 
		strFileName := GetUniqueFileName(strFileName);
		ImageNameOnServer := ImageFolder +  '/' + strFileName; 
		sToFileName := IncludeTrailingPathDelimiter(ServerFolder) + strFileName;
 		try 
    	PostedFile.SaveAs(sToFileName);
			Result:=true;
		except 
			on E:exception do
			begin
				ErrorMSG:=E.Message;
				Result:=false;
			end;
		end;
	end;		
end; //UploadFile	

constructor THtmlInputFile.Create;
begin
	inherited Create;
end;

end.
