Dicas - Como habilitar o download de arquivos a partir uma página ASP.NET

Veja nesta dica, como habilitar download de arquivos em uma página ASP.NET.

Aqui está como habilitar o download de arquivos de um servidor a partir de um página asp.net (aspx). Insira um controle Button em um formulário aspx (WebForm1:TWebForm1) e atribua o código a seguir ao evento Click:

procedure TWebForm1.Button1_Click(sender: System.Object; e: System.EventArgs) ; var FileToDownload: string; begin //certifique-se que o arquivo existe! FileToDownload := 'c:\ServerTest.txt'; DownloadFile(FileToDownload,'LocalTest.txt') ; end;
Listagem 1. Código do evento click do botão

Aqui está a função DownloadFile (certifique-se que System.IO foi adicionado aos uses de seu code-behind, ou à unit onde DownloadFile é definido):

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;
Listagem 2. Função DownloadFile

Finalizo aqui essa dica, espero que tenham gostado e aprendido a realizar downloads de arquivos em uma página asp.net. Até o próximo.

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

Artigos relacionados