Drop a Button web control on an aspx web form (WebForm1:TWebForm1) and assign the next code for the Click event:
~~~~~~~~~~~~~~~~~~~~~~~~~
procedure TWebForm1.Button1_Click(sender: System.Object; e: System.EventArgs) ;
var
FileToDownload : string;
begin
FileToDownload := 'c:\ServerTest.txt'; //make sure this exists!!!
DownloadFile(FileToDownload,'LocalTest.txt') ;
end;
Here's the DownloadFile function (make sure you add the System.IO to the uses list in your code-behind, or the unit where DownloadFile is defined):
procedure DownloadFile(const FilePath : String; const FileName : String =''; const ContentType : String = '') ;
type
TStringArray = array of string;
var
DownloadFileName : string;
fi : FileInfo;
StartPos, FileSize, EndPos : System.Int64;
Range : string;
StartEnd : TStringArray;
begin
If Not System.IO.File.Exists(FilePath) Then Exit;
StartPos := 0;
fi := FileInfo.Create(FilePath) ;
FileSize := fi.Length;
EndPos := FileSize;
HttpContext.Current.Response.Clear() ;
HttpContext.Current.Response.ClearHeaders() ;
HttpContext.Current.Response.ClearContent() ;
Range := HttpContext.Current.Request.Headers['Range'];
If Assigned(Range) AND (Range <> '') Then
Begin
StartEnd := Range.Substring(Range.LastIndexOf('=') + 1).Split(['-']) ;
If Not (StartEnd[0] = '') Then
StartPos := Convert.ToInt64(StartEnd[0]) ;
End;
If (System.Array(StartEnd).GetUpperBound(0) >= 1) And (Not (StartEnd[1] = '')) Then
EndPos := Convert.ToInt64(StartEnd[0])
Else
EndPos := FileSize - StartPos;
If EndPos > FileSize Then EndPos := FileSize - StartPos;
HttpContext.Current.Response.StatusCode := 206;
HttpContext.Current.Response.StatusDescription := 'Partial Content';
HttpContext.Current.Response.AppendHeader('Content-Range', 'bytes ' + StartPos.ToString + '-' + EndPos.ToString + '/' + FileSize.ToString) ;
If Not (ContentType = '') And (StartPos = 0) Then
Begin
HttpContext.Current.Response.ContentType := ContentType;
End;
If FileName = '' Then
DownloadFileName := fi.Name
else
DownloadFileName := FileName;
HttpContext.Current.Response.AppendHeader('Content-disposition', 'attachment; filename=' + DownloadFileName) ;
HttpContext.Current.Response.WriteFile(FilePath, StartPos, EndPos) ;
HttpContext.Current.Response.&End;
End; (*DownloadFile*)
~~~~~~~~~~~~~~~~~~~~~~~~~
Delphi tips navigator:
» How to disable Context menu in a TWebBrowser
« How to show week numbers in a TDateTimePicker

