Solved

Redirect or response.write after Content-Disposition how?

Posted on 2002-05-16
26
1,507 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
 

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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

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…
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…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

758 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

24 Experts available now in Live!

Get 1:1 Help Now