Solved

Redirect or response.write after Content-Disposition how?

Posted on 2002-05-16
26
1,528 Views
Last Modified: 2007-11-27
Hi,

I've written a script that will download files form our webserver. The file is opened in a new window via Javascript. The window should be closed by that same javascript after 2.5 seconds but it isn't stable. Now and then the window isn't closed.

Is it possible to do a response.redirect or .write after the following script is executed? If so, how?

Script:
<!--#include virtual="/NR/System/Access/Authenticate.inc"-->
<%
Response.Expires = 0
Dim sFileUrl, sFilePath, sPostingGuid, sFileExtention, sFileName, oPosting

Function getBinaryFile(fileSpec)
      Dim adTypeBinary
      Dim oStream
           
      adTypeBinary       = 1
      set oStream       = Server.CreateObject("ADODB.Stream")
     
      oStream.Open
      oStream.Type       = adTypeBinary
     
      oStream.LoadFromFile fileSpec
     
      getBinaryFile      = oStream.read
     
      set oStream      = nothing
end Function

sFileUrl             = Request.QueryString("fileurl")
sFilePath             = Replace(sFileUrl,"http://" & Request.ServerVariables("SERVER_NAME") & "/yamadocs", "")
sFilePath             = "d:\yamanet\documents" & Replace(sFilePath,"/","\")
sFileName       = Mid(sFileUrl,InStr(sFileUrl,"{"))
sPostingGuid      = Left(sFileName,InStrRev(sFileName,".") - 1)
sFileExtention      = Mid(sFileName,InStrRev(sFileName,"."))

Set oPosting       = AutoSession.Searches.GetByGUID(sPostingGuid)
sFileName      = oPosting.DisplayName
Set oPosting       = Nothing

Response.ContentType      = "application/x-unknown"

Response.AddHeader "Content-Disposition","attachment; filename=" & chr(34) & sFileName & sFileExtention & chr(34)
Response.BinaryWrite getBinaryFile(sFilePath)
%>

0
Comment
Question by:ironeye
  • 11
  • 8
  • 3
  • +2
26 Comments
 
LVL 23

Expert Comment

by:b1xml2
ID: 7013375
You cannot use the Response.Redirect if any content is sent to the client. Setting the Response.Buffer = True and use the Server.Execute or Server.Transfer to do what you want. Response.Redirect sends a HTTP Header to the client but Server.Transfer /Server.Execute happens server-side.

Server.Transfer "page.asp"

or

Server.Execute "page.asp"

Do not add any query strings to the URL. Both Server methods preserve the Request Object. The only difference between Transfer() and Execute() is where control will end. In the Transfer() method, control is passed over to the other page and does not return to the original page. Execute however, passes control to the page from the original page and receives it back =)
0
 

Author Comment

by:ironeye
ID: 7013381
hmmm...

How should I pass the fileurl then? I could write it in a cookie but the company I work for don't like me using cookies.
0
 

Author Comment

by:ironeye
ID: 7013408
let's see if I got it right:

If changed the downloaddocument.asp into this:
Session("sFilePath") = sFilePath
Session("sFile")      = sFileName & sFileExtention

Server.Execute "dodownload.asp"

Session.Contents.RemoveAll()

Response.write "Dos it work now?"

The used variables are filled in the script.

dodownload.asp looks like this:
Function getBinaryFile(fileSpec)
     Dim adTypeBinary
     Dim oStream
         
     adTypeBinary      = 1
     set oStream      = Server.CreateObject("ADODB.Stream")
     
     oStream.Open
     oStream.Type      = adTypeBinary
     
     oStream.LoadFromFile fileSpec
     
     getBinaryFile     = oStream.read
     
     set oStream     = nothing
end Function

Response.ContentType     = "application/x-unknown"

Response.AddHeader "Content-Disposition","attachment; filename=" & chr(34) & Session("sFile") & chr(34)
Response.BinaryWrite getBinaryFile(Session("sFilePath"))

the result is that the response.write in downloaddocument.asp statement isn't executed. Any suggestions?
0
Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

 

Author Comment

by:ironeye
ID: 7013411
forgot to mention; the user is prompted to downlaod the file, so that works.
0
 
LVL 23

Expert Comment

by:b1xml2
ID: 7013484
From MSDN, it is clear that once you use the Response.BinaryWrite method, you cannot use the Response.Write method since that actually goes into the Stream being sent down to the client
0
 
LVL 23

Expert Comment

by:b1xml2
ID: 7013488
what you could try is the following simple example:-

<a href="data.dlg" target="_blank">Download Me</a>

data.dlg
========
Register this mime-type with the same settings as .asp under the IIS MMC. Then you can write your code and no window will open as the browser will assume that a download is happening.
0
 

Author Comment

by:ironeye
ID: 7013534
I've tried this but it acts the same as when I'm using an asp-file. see the following images for the information that's presented to the client:

http://www.endoria.net/upload/index.php/1198418573 Here you can see that the first thing the script is trying to download is actualy an htm file, you must choose "open".

http://www.endoria.net/upload/index.php/2793721609 now the actual file is presented.

http://www.endoria.net/upload/index.php/2235644666 the script forces a identifying filename, and you can choose the location you want to save the file to.

This is weird.
0
 
LVL 29

Expert Comment

by:Göran Andersson
ID: 7016271
As you open a file to download, you can't write anything more after the file. There is simply no window to write it to.

Maybe you should fix the Javascript instead...

What does it look like?
0
 

Author Comment

by:ironeye
ID: 7023220
in the last case, i'm not using a javascipt. It's a direct link to the asp-file that forces the download.
0
 
LVL 29

Expert Comment

by:Göran Andersson
ID: 7024232
If you are not using a javascript, then you can't close the window.

There is no way for the download to close the window. It has to be done from the page with the link.
0
 

Author Comment

by:ironeye
ID: 7028863
I have been using javascipt to open the window, wait 2 seconds and then close the window. But the issue is that sometimes this doesn't work, the window simply isn't closed.

This setup is to unstable to run in an intranet for 1800 employees.
0
 
LVL 29

Expert Comment

by:Göran Andersson
ID: 7029208
Ok, you have a javascript after all.

What does it look like?
0
 

Author Comment

by:ironeye
ID: 7029215
I had a javascript. It was:

function openandclose(url) {
      var NewWindow = window.open(url, 'DocDownload', 'status=yes,toolbar=yes,menubar=yes,width=500,height=300');
      setTimeout('NewWindow.close()',2500);
}
0
 
LVL 29

Expert Comment

by:Göran Andersson
ID: 7029268
This might be a bit more stable:

var popWindow;

function closePop(delay)
{
     if (popWindow) {
          setTimeout('popWindow.close();',delay);
     } else {
          setTimeout('closePop('+delay+');',100);
     }
}

function openAndClose(url)
{
     popWindow = window.open(url, 'DocDownload', 'status=yes,toolbar=yes,menubar=yes,width=500,height=300');
     closePop(2500);
}
0
 

Author Comment

by:ironeye
ID: 7029297
I've implemented your solution and it works when downloading word-documents. Whenever I attempt to download a PDF I get an action cancelled message in the opened window, after this message occurs the javascript doesn't close the window.

This is the instabillity I reffered to.

This isn't the case for all pdf-documents, some work. It's strange.
0
 
LVL 29

Expert Comment

by:Göran Andersson
ID: 7029354
Are you opening the download script from your first posting in the popup window? If so, I believe that's what causing the problem.

Open this page in the popup window:

<%
Response.Expires=-1
%>
<html>
<head>
</head>
<body onLoad="document.location='download.asp?fileurl=<%=Request.QueryString("fileurl")%>';">
</body>
</html>

Change download.asp to whatever your script is named.

The download is locking the popup window. By putting this page in between, it separates the download from the popup window, enabling you to close it.
0
 

Author Comment

by:ironeye
ID: 7029368
I appreciate your help a lot. Done as you suggested but then I'm back to the point i mentioned earlier in the reply with the links to the images.

http://www.endoria.net/upload/index.php/1198418573
http://www.endoria.net/upload/index.php/2793721609
http://www.endoria.net/upload/index.php/2235644666 

The first thing that the script tries to download is the htm file,nog the actual binairy data.
0
 
LVL 29

Expert Comment

by:Göran Andersson
ID: 7029501
Strange, I don't get that. But, then I don't have an html file...

I have the page with the openAndClose script, that opens a popup with the short code I presented last. That page opens Download.asp that has code similar to the first script you posted, e.g. it opens the data file and writes it to the response stream.

How does this differ from your setup, and where in the process is the html file?
0
 

Author Comment

by:ironeye
ID: 7036430
It's exactly the same. The html-file it attempts to download is the download.asp file. It doesn't generate any html, that's the strange part.

I get the same when using hotmail.com. If a message has an attachement and I download it the first file that is being downloaded is the getmsg.htm when I choose open the next pop-up is presented wherein the real attachement is presented for download.
0
 
LVL 29

Expert Comment

by:Göran Andersson
ID: 7036789
I have never gotten this anywhere. It rather sounds like there is something wrong with your IE installation... Have you tried this on a different computer?
0
 

Author Comment

by:ironeye
ID: 7036793
yes and it results in the same.

Does your setup includes frames or not? Mine does.
0
 
LVL 29

Accepted Solution

by:
Göran Andersson earned 150 total points
ID: 7036807
I have tested this with the page in a frameset. There is no difference, it works just fine.

Here's my complete code:

-----Frames.asp-----
<html>
<head>
<title></title>
</head>
<frameset cols="*,*">
     <frame src="Default.asp">
     <frame src="test.html">
</frameset>
</html>
--------------------

-----Default.asp-----
<html>
<head>

<script>

var popWindow;

function closePop(delay)
{
     if (popWindow) {
          setTimeout('popWindow.close();',delay);
     } else {
          setTimeout('closePop('+delay+');',100);
     }
}

function openAndClose(url)
{
     popWindow = window.open(url, 'DocDownload', 'status=yes,toolbar=yes,menubar=yes,width=500,height=300');
     closePop(2500);
}

</script>

</head>
<body>

<form>
<input type="button" value="temp.pdf" onClick="openAndClose('download.asp?fileurl=temp.pdf');">
<input type="button" value="winzip70.exe" onClick="openAndClose('download.asp?fileurl=winzip70.exe');">
</form>

</body>
</html>
--------------------

-----download.asp-----
<%
Option Explicit
Response.Expires = -1
Response.Buffer=True

Const adTypeBinary=1

Dim strFileUrl, strFilePath

Function getBinaryFile(fileSpec)
     Dim oStream

     Set oStream = Server.CreateObject("ADODB.Stream")
     oStream.Open
     oStream.Type = adTypeBinary
     oStream.LoadFromFile fileSpec
     getBinaryFile = oStream.read
     Set oStream = Nothing
End Function

strFileUrl = Request.QueryString("fileurl")
strFilePath = Server.MapPath(strFileUrl)

Response.ContentType = "application/x-unknown"

Response.AddHeader "Content-Disposition","attachment; filename=""" & strFileUrl & """"
Response.BinaryWrite getBinaryFile(strFilePath)
%>
--------------------

-----test.html-----
<html>
<head>
</head>
<body>
Hello world, this is a test...
</body>
</html>
--------------------
0
 
LVL 15

Expert Comment

by:gladxml
ID: 8803584
No comment has been added lately and it seems that this question have been abandoned. So it's time to clean up this TA.

I will leave a recommendation in the Cleanup topic area that this question or invite a Moderator to close this question if there's no reply from you after seven days.

In the absence of responses, I will recommend the following:

To accept the comment and points awarded to GreenGhost

** PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER **


Just trying to help for the cleanup...
gladxml
0
 
LVL 1

Expert Comment

by:jroth-haj
ID: 11617934
Here is an other Solution for automated File Download with a Response:

You have a form that send a Filename (file) and a password (pw)

-----dlform.asp-----
<html>
<head>
</head>
<body>
<form action="dlresponse.asp" METHOD="post" target="_self">
Filename: <input type="text" name="file"><br>
Password: <input type="password" name="pw">
<input type="submit">
</form>
</body>
</html>
--------------------

-----dlresponse.asp.asp-----
When the body was loaded the user will be redirected to download.asp

// here you will check the password and if the file exists

// if anything is false you will output html code with an error message and an link back to dlform.asp

// if all ist correct you will
   1) save the real filename and path in the session and
   session("Filename")=s_FileName
   session("FilenameWithPath")=s_File
   session("FileSizeInByte")=s_FileSize

   2) output the following html code

<html>
<head>
</head>
<body onload="location.href='download.asp'">

<-- put some other information of the file here like filesize, description,... -->

<-- put a link to download.asp here -->

If the download not starts klick <a href="download.asp">here</a>!

</body>
</html>
----------------------------


-----download.asp-----
<-- whenn this page is loaded the user will become an "save as" dialog -->

<%
s_FileName=session("Filename")
s_File=session("FilenameWithPath")
s_FileSize=session("FileSizeInByte")

// read the real filename from the session and start the download procedure

  s_FileType = lcase(Right(s_FileName, 4))

    Select Case s_FileType
      Case ".zip"
        s_ContentType = "application/zip"
      case ".pdf"
        s_ContentType = "application/pdf"
      Case ".doc"
        s_ContentType = "application/msword"
     Case ".xls"
        s_ContentType = "application/vnd.ms-excel"
     Case ".ppt"
        s_ContentType = "application/vnd.ms-powerpoint"
     Case ".gif"
        s_ContentType = "image/gif"
     Case ".jpg"
        s_ContentType = "image/jpeg"
     case ".jpe"
        s_ContentType = "image/jpeg"
     Case "jpeg"
        s_ContentType = "image/jpeg"
     Case ".bmp"
        s_ContentType = "image/bmp"
     Case Else
        s_ContentType = "application/octet-stream"
   End Select

  Response.Clear
  Response.Buffer = false
  Response.ContentType = s_ContentType
  Response.AddHeader "Content-transfer-encoding", "binary"
  Response.AddHeader "Content-Length", s_FileSize
  //*** do not open Files in Browser --> attachmet
    Select Case s_FileType
      case ".pdf"
        Response.AddHeader "Content-Disposition", "attachment; filename=""" & s_FileName & """"
      case ".txt"
        Response.AddHeader "Content-Disposition", "attachment; filename=""" & s_FileName & """"
      case else
        Response.AddHeader "content-disposition","filename=""" & s_FileName & """"
    End Select

  Response.BinaryWrite getBinaryFile(s_File)
  Response.End
%>
----------------------


thats it!

Greetings from Hannover, Germany
0
 
LVL 1

Expert Comment

by:jroth-haj
ID: 11629313
Here is a correction for problems with Netscape

without this correction Netscape shows in the Save As Dialog the filename as filename.extension.asp

-----dlresponse.asp.asp-----
<body onload="location.href='download.asp?FileName'">
...
If the download not starts klick <a href="download.asp?FileName">here</a>!
...
--------------------------------
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say 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

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…
Hello, all! I just recently started using Microsoft's IIS 7.5 within Windows 7, as I just downloaded and installed the 90 day trial of Windows 7. (Got to love Microsoft for allowing 90 days) The main reason for downloading and testing Windows 7 is t…
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

839 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