views:

200

answers:

2

It's a bit complicated this one... Lets say I have a listing of PDF files displayed in the user's browser. Each filename is a link pointing not to the file, but to an ASP page, say

<--a href="viewfile.asp?file=somefile.pdf">somefile.pdf</a>  

I want viewfile.asp to fetch the file (I've done that bit OK) but I then want the file to be loaded by the browser as if the user had opened the PDF file directly. And I want it to open in a new tab or browser window.

here's (simplified) viewfile.asp:

<%
var FileID   = Request.querystring ("file") ;
var ResponseBody = MyGETRequest (SomeURL + FileID) ;

if (MyHTTPResult == 200)
    { 
    if (ExtractFileExt (FileID).toLowerCase = "pdf")
        {
        ??????  // return file contents in new browser tab
        }        
....
%>
+1  A: 

I would do this.

<a href="viewfile.asp?file=somefile.pdf" target="_blank">somefile.pdf</a>

That way this opens in a new window/tab. Any server side language does not have control of the browser.

To serve it as a PDF, call

<% response.ContentType="application/pdf" %>
Daniel A. White
Thanks for that. What about the hard part of my question (returning the PDF as a PDF)! So I'm sitting in my ASP page at the server with the contents of the PDF file (which I have retrieved from a third website) in the response body. What do I need to do to it to send it back to the browser so that the browser "sees" it as a PDF?
Brilliant. Works a treat. For filetypes other than PDF, I set the ContentType to 'application/octet-stream'. For some reason, the browser tries to open those files with Acrobat reader as well. Tried it on FF as well as Chrome - same behaviour. Any ideas?
Try serving those other files with their respective mime type.
Daniel A. White
Yes, but isn't 'application/octet-stream' a MIME type? The other files are a filetype that doesn't have a MIME type and the intention eventually is to receive them in the browser with some client side JS and process them for display. I can't because the browser insists on trying to render them to the Acrobat reader. I expected with a Content type of 'application/octet-stream' I would at least get a file download dialog displaying in the browser.
Problem solved. A combination of things, but mostly: - a wayward single quote inside the content type string "'application/pdf" - a call to toLowerCase, when it should have been toLowerCase () - missing "=" in comparison, i.e. if (Filetype = "pdf"), which should have been if (Filetype == "pdf")I hate this language sometimes.
+1  A: 

As Daniel points out you can control whether to open in a new window but not a new tab. If the user has configured their browser so that new windows should open in new tabs (like I do) then you're golden. If not it will open in a new window. You can't control tabs.

Marcus
Gotcha. Thanks.