Link to home
Start Free TrialLog in
Avatar of ironeye
ironeye

asked on

Redirect or response.write after Content-Disposition how?

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)
%>

Avatar of b1xml2
b1xml2
Flag of Australia image

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 =)
Avatar of ironeye
ironeye

ASKER

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.
Avatar of ironeye

ASKER

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?
Avatar of ironeye

ASKER

forgot to mention; the user is prompted to downlaod the file, so that works.
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
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.
Avatar of ironeye

ASKER

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.
Avatar of Göran Andersson
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?
Avatar of ironeye

ASKER

in the last case, i'm not using a javascipt. It's a direct link to the asp-file that forces the download.
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.
Avatar of ironeye

ASKER

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.
Ok, you have a javascript after all.

What does it look like?
Avatar of ironeye

ASKER

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);
}
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);
}
Avatar of ironeye

ASKER

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.
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.
Avatar of ironeye

ASKER

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.
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?
Avatar of ironeye

ASKER

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.
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?
Avatar of ironeye

ASKER

yes and it results in the same.

Does your setup includes frames or not? Mine does.
ASKER CERTIFIED SOLUTION
Avatar of Göran Andersson
Göran Andersson
Flag of Sweden image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
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
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>!
...
--------------------------------