Dicas - Como habilitar o download para uma página ASP.NET

Veja nesta dica em ASP.NET para Delphi 2005, como habilitar o download em sua webpage.

Como habilitar o download para uma página ASP.NET

Aqui é como habilitar o download de arquivos do servidor de página aspx.  

Arraste um Botão no webform (WebForm1:TWebForm1) e nomeie o próximo código para o evento Click.

 

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;

 

Aqui é a DownloadFile funcionando (tenha certeza de que você acrescentou o namespace System.IO a uses).

 

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*)

Ebook exclusivo
Dê um upgrade no início da sua jornada. Crie sua conta grátis e baixe o e-book

Artigos relacionados