Solved

Text getting appended to file downloaded using Response.BinaryWrite

Posted on 2004-09-08
6
472 Views
Last Modified: 2008-03-06
I have been using the code that follows to download files from a web application.  It seems to work fine for all files except text files.  It is appending a bunch of text to the end of the file I download.  The text is the HTML code that is part of the Download.asp file I downloaded the file from.  Here is the entire code from download.asp:

<%@Language="VBScript"%>

<%
Option Explicit

Dim PID
PID = Request.QueryString("PID")
%>

<html>
<head>
      <link type="text/css" rel="stylesheet" href="../General/style.css">
    <TITLE>My Title</TITLE>
    <script language="javascript">
            function ReloadParent()
            {
                  window.opener.location.href='ProjFiles.asp?Actn=Edit&PID=<%=PID%>';
            }
    </script>
</head>
<body leftMargin=0 rightmargin=0 topmargin=0 onLoad="clock();">

<!--#include file="../General/Globals.inc"-->
<%
Src = "Download"
%>
<!--#include file="../General/ConnStr.inc"-->
<!--#include file="../General/VerifyUsrOpen.inc"-->
<!--#include file="../General/Title.inc"-->
<!--#include file="../General/VerifyUsrClose.inc"-->

<%
Dim strFileLocation, strRootPath

Dim FID
FID = Request.QueryString("FID")

Dim FileName
FileName = Request.QueryString("FileName")

If FID <> "" Then
      Dim ConnGetRootPath, SQLGetRootPath, RSGetRootPath
      Set ConnGetRootPath = Server.CreateObject("ADODB.Connection")
            ConnGetRootPath.Open ConnStr
            SQLGetRootPath =      "SELECT Root_Path_For_Files " &_
                                          "FROM t_System_Information"
            Set RSGetRootPath = ConnGetRootPath.Execute(SQLGetRootPath)
            strRootPath = RSGetRootPath("Root_Path_For_Files")
            RSGetRootPath.Close
            Set RSGetRootPath = Nothing
            ConnGetRootPath.Close
            Set ConnGetRootPath = Nothing
            
      Dim ConnGetFileLocation, SQLGetFileLocation, RSGetFileLocation
      Set ConnGetFileLocation = Server.CreateObject("ADODB.Connection")
            ConnGetFileLocation.Open ConnStr
            SQLGetFileLocation =      "SELECT File_Location " &_
                                                "FROM t_Files " &_
                                                "WHERE [File_ID] = "& FID &""
            Set RSGetFileLocation = ConnGetFileLocation.Execute(SQLGetFileLocation)
            strFileLocation = RSGetFileLocation("File_Location")
            RSGetFileLocation.Close
            Set RSGetFileLocation = Nothing
            ConnGetFileLocation.Close
            
            
      If Request("Download.x") = "" Then      
            ' Update record in t_Files that the file is now checked out
            Dim ConnCheckOut, SQLCheckOut, RSCheckOut
            Set ConnCheckOut = Server.CreateObject("ADODB.Connection")
                  ConnCheckOut.Open ConnStr
                  SQLCheckOut =      "exec usp_FileCheckInOut " &_
                                          "@Type = 'CheckOut', " &_
                                          "@FileID = "& FID &", " &_
                                          "@CheckedBy = "& UID &""                                    
                  Set RSCheckOut = ConnCheckOut.Execute(SQLCheckOut)
                  ConnCheckOut.Close
                  Set ConnCheckOut = Nothing
      End If
            
      Function downloadFile( intFileID, strFilePath, strFile, strDownloadFilename )
            Dim strFilename,objStream,objFilesystem,objFilestream
            Dim intFileLength    
            ' get full path of specified file
            strFilename = strFilePath
            ' clear the buffer
            Response.Buffer = True
            Response.Clear

            ' create stream
            Set objStream = Server.CreateObject("ADODB.Stream")
            objStream.Open

            ' set as binary
            objStream.Type = 1

            ' check that the file exists
            Set objFilesystem = Server.CreateObject("Scripting.FileSystemObject")
          
            ' get length of file
            Set objFilestream = objFilesystem.GetFile( strFilename )
            intFilelength = objFilestream.size
      
            objStream.LoadFromFile( strFilename )
            if err then
                  Response.Write("<h1>Error: </h1>" & err.Description & "<p>")
                  Response.End
            end if
          
            'format strFileName
            if Len( Trim(strDownloadFilename) ) > 0 then
                  strDownloadFilename = Trim( strDownloadFilename )
            else
                  strDownloadFilename = objFilestream.name
            end if

            ' send the headers to the users browser
            Response.AddHeader "Content-Disposition", "attachment; filename=" & strDownloadFilename
            Response.AddHeader "Content-Length", intFilelength
            Response.Charset = "UTF-8"
            Response.ContentType = "application/octet-stream"

            ' output the file to the browser
            Response.BinaryWrite objStream.Read
            Response.Flush

            ' tidy up
            objstream.Close
            Set objstream = Nothing
      End Function
      
      If request("Download.x") <> "" Then
            Call downloadFile(Request.QueryString("FID"), strRootPath & strFileLocation & Request.QueryString("FileName"), Request.QueryString("FileName"), Request.QueryString("FileName"))
      End If
End If
%>
<form name="frmDownload" method="post" action="Download.asp?FID=<%=FID%>&FileName=<%=FileName%>" style="display:inline;">
<table width="100%" align="center">
      <tr valign="center">
            <td align="center">
                  <br><br><br>
                  Your file is ready to download.  Click here to start
                  <br><br>
                  <input type="image" name="Download" src="../Images/DownloadBtn.jpg" value="DOwnload" alt="Download File" align="absmiddle" onclick="ReloadParent();">
                  <br><br><br><br><br>
                  Click <a href=javascript:self.close()><span class="IrishGreen8"><u>here</u></span></a> to close this window when finished.
            </td>
      </tr>
</table>
</body>
</form>
</html>




Here is what a file looks like after I download it:
[MSILoader]
MSIFileName=ProjectInfoSetup.msi

<form name="frmDownload" method="post" action="Download.asp?FID=177&FileName=Setup.Ini" style="display:inline;">
<table width="100%" align="center">
      <tr valign="center">
            <td align="center">
                  <br><br><br>
                  Your file is ready to download.  Click here to start
                  <br><br>
                  <input type="image" name="Download" src="../Images/DownloadBtn.jpg" value="DOwnload" alt="Download File" align="absmiddle" onclick="ReloadParent();">
                  <br><br><br><br><br>
                  Click <a href=javascript:self.close()><span class="IrishGreen8"><u>here</u></span></a> to close this window when finished.
            </td>
      </tr>
</table>
</body>
</form>
</html>



I should only have in the file the following text:
[MSILoader]
MSIFileName=ProjectInfoSetup.msi




Can anybody tell me why the HTML from download.asp is getting appended to the end of my downloaded file?
0
Comment
Question by:ABaruh
  • 3
  • 2
6 Comments
 
LVL 31

Expert Comment

by:alorentz
ID: 12008568
You do a response.redirect:

If request("Download.x") <> "" Then
          Call downloadFile(Request.QueryString("FID"), strRootPath & strFileLocation & Request.QueryString("FileName"), Request.QueryString("FileName"), Request.QueryString("FileName"))
   response.redirect "someotherpage.asp"
End If
0
 
LVL 7

Author Comment

by:ABaruh
ID: 12008660
So I want to do a response redirect after calling the function?
0
 
LVL 3

Expert Comment

by:Ayesha_K
ID: 12008733
your function might becreating some error and hence not closing the stream object thats why its writting the things below it ... try this

________________________________

Function downloadFile( intFileID, strFilePath, strFile, strDownloadFilename )
on error goto errHandler
          Dim strFilename,objStream,objFilesystem,objFilestream
          Dim intFileLength    
          ' get full path of specified file
          strFilename = strFilePath
          ' clear the buffer
          Response.Buffer = True
          Response.Clear

          ' create stream
          Set objStream = Server.CreateObject("ADODB.Stream")
          objStream.Open

          ' set as binary
          objStream.Type = 1

          ' check that the file exists
          Set objFilesystem = Server.CreateObject("Scripting.FileSystemObject")
         
          ' get length of file
          Set objFilestream = objFilesystem.GetFile( strFilename )
          intFilelength = objFilestream.size
     
          objStream.LoadFromFile( strFilename )
          if err then
               Response.Write("<h1>Error: </h1>" & err.Description & "<p>")
               Response.End
          end if
         
          'format strFileName
          if Len( Trim(strDownloadFilename) ) > 0 then
               strDownloadFilename = Trim( strDownloadFilename )
          else
               strDownloadFilename = objFilestream.name
          end if

          ' send the headers to the users browser
          Response.AddHeader "Content-Disposition", "attachment; filename=" & strDownloadFilename
          Response.AddHeader "Content-Length", intFilelength
          Response.Charset = "UTF-8"
          Response.ContentType = "application/octet-stream"

          ' output the file to the browser
          Response.BinaryWrite objStream.Read
          Response.Flush

          ' tidy up
          objstream.Close
          Set objstream = Nothing
errHandler:
response.write (err.description)
     End Function
0
Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 31

Accepted Solution

by:
alorentz earned 500 total points
ID: 12008749
>>So I want to do a response redirect after calling the function?

Yep, just like I showed in the example I gave...
0
 
LVL 7

Author Comment

by:ABaruh
ID: 12008907
actually, I got ASP Error 0156 Header Error when I tried to use the Reponse.Redirect

I actually solved the problem by adding Response.end instead of Response.Redirect.  Nevertheless, I am going to assign you the points as you got me thinking in that direction.
0
 
LVL 31

Expert Comment

by:alorentz
ID: 12008999
You got that error because of your Response.Buffer setting.

I would've said response.end, but figured you wanted to send the user somewhere friendly instead of blank page..
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I have helped a lot of people on EE with their coding sources and have enjoyed near about every minute of it. Sometimes it can get a little tedious but it is always a challenge and the one thing that I always say is:  The Exchange of information …
I would like to start this tip/trick by saying Thank You, to all who said that this could not be done, as it forced me to make sure that it could be accomplished. :) To start, I want to make sure everyone understands the importance of utilizing p…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question