Solved

Text getting appended to file downloaded using Response.BinaryWrite

Posted on 2004-09-08
6
464 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
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

I recently decide that I needed a way to make my pages scream on the net.   While searching around how I can accomplish this I stumbled across a great article that stated "minimize the server requests." I got to thinking, hey, I use more than one…
I was asked about the differences between classic ASP and ASP.NET, so let me put them down here, for reference: Let's make the introductions... Classic ASP was launched by Microsoft in 1998 and dynamically generate web pages upon user interact…
This video discusses moving either the default database or any database to a new volume.
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

707 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now