Display download window from JSP

Hi,
I hava a links to PDF files on a JSP. These PDF files are not in the web server virtual path. When user clicks a link in the browser then it should display download or open from current location window. How can I do this. Please help me.
Thanks,
Simi

The following code you post the complete filepath to a servlet
Recommendations:
Replace the filepath by a pointer to a session-variable or database-entry
by which you can dynamicaly retrieve and keep the full path on the serverside.
Code:
in your for jsp insert:
use &lt;a href="#" onClick="downloadform.FILENAME.value="<%= your dynamic path here %>">download &lt;%= your dynamic path here %>&lt;/a>
&lt;form method=post name=downloadform action="servlet/DownloadServlet">
&lt;input type=text name=FILENAME>
&lt;input type=submit value="get file">
&lt;/form>
&lt;/html>
* Class : DownloadServlet
* function :
* create an file outputstream
* Usage :
* create an file outputstream
* doGet is functionally disabled
* to hide parameters from the adressbar
* Date : 05-03-2002
* By : [email protected]
import java.io.*;
import java.net.*;
import java.util.*;
import javax.servlet.http.*;
import javax.servlet.*;
public class DownloadServlet extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
super.init(config);
protected void doGet( HttpServletRequest request
, HttpServletResponse response) throws ServletException
, IOException {
StringBuffer sb = new StringBuffer();
ServletOutputStream out = response.getOutputStream();
sb.append("Sorry, getter method is no longer supported\n");
protected void doPost( HttpServletRequest request
, HttpServletResponse response) throws ServletException
, IOException {
ServletOutputStream out = response.getOutputStream();
ServletContext context = this.getServletConfig().getServletContext();
HttpSession session = request.getSession();
String file = "";
StringBuffer sbe = new StringBuffer();
file = request.getParameter("FILENAME");
String fileName = file.substring(file.lastIndexOf("\\")+1); // Windows
String fileName = file.substring(file.lastIndexOf("/")+1); // UNIX or Linux
String fileName = file.substring(file.lastIndexOf("\\")+1);
File downloadfile = new File(file);
long filesize = downloadfile.length();
if ( !downloadfile.exists() ) {
sbe.append( "<p style='color:#000080;font-family:arial'>");
sbe.append( "<b>The system cannot find file <i>'" + fileName + "'</i></b><br>" );
sbe.append( "<b>It may have been (re)moved</b><br>" );
sbe.append( "Contact you administrator for information" );
sbe.append( "</p>");
out.print(sbe.toString());
} else {
try {
// Read the file requestparameter.
// This should be a file relative to the directory
int lastDot = file.lastIndexOf(".");
String ext = file.substring(lastDot+1).toLowerCase();
String contenttype = "text/html"; // DEFAULT CONTENTTYPE
contenttype = "application/octet-stream";
response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ";");
response.setHeader("Cache-Control", "Pragma");
response.setContentType(contenttype);
response.setContentLength((int)filesize);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream bos = new BufferedOutputStream(out);
// stream the file back to the client
byte[]buffer = new byte[1024];
int size;
size= bis.read(buffer);
while ( size != -1 ) {
bos.write( buffer, 0, size );
size = bis.read(buffer);
bis.close();
bos.flush();
} catch ( Exception e ) {
response.reset();
response.setContentType("text/html");
sbe.append("<h1 style='color:#800000;font-family:arial'>Error:</h1>");
sbe.append( "<p style='color:#000080;font-family:arial'>");
sbe.append( "<b>An error occured while trying to retrieve <i>'" + fileName + "'</i></b><br>" );
sbe.append( "Contact you administrator for information" );
sbe.append( "</p>");
out.print(sbe.toString());

Similar Messages

  • How to import and display an applet from JSP

    i m using netbeans 5.0
    i have class named myapplet.class
    and jsp named myjsp.jsp
    now i want to access(import) this myapplet.class from jsp
    also i want to display this applet from this jsp
    i am able to do either thing but not both
    so please help me it is so urgent and important for me bcoz
    i have to complete my project as early as possible
    Thanks in advance

    my jsp source file page path is D:\Reliance
    project\WebApplication3\web\
    and classes path is D:\Reliance
    project\WebApplication3\build\web\WEB-INF\classes\
    so problem is that if i want to use myapplet.class
    then i have to put my class in D:\Reliance
    project\WebApplication3\build\web\WEB-INF\classes\
    location
    but at that time i am not able to display this applet
    on my jsp
    if i put my myapplet.class in
    D:\Reliance project\WebApplication3\web\ then i m
    able to display
    applet but not able to access(import) this class
    hope you will got the problem!!!
    thanks for your reply !!!try to set the path of your applet on jsp something like this
    "WEB-INF/classes/myclass.class"

  • IE 6 giving the problems while downloading content from JSP File

    Hi,
    I am trying to download the file JSP, Blwo is the test code
    <%
    response.setContentType("application/csv");
    response.setHeader("Content-Disposition", "filename=commissionData.csv;");
    %>
    This     is     test
    This     is     test1
    This     is     test2
    When I try to load this file in IE 6, The error message comes like below
    "Internet Explorer cannot download MyJsp.jsp from localhost.
    Internet Explorer was not able to open this Internet site. The
    requested site is either unavailable or cannot be found. Please try
    again later."
    Can anyone help me in this regards.
    Thanks in advance
    Shailesh S Deshpande

    works fine for me on Tomcat 4.
    What server are you using?
    Is it running? Try restarting it.

  • Mission control: display only windows from a space?

    I have a lot of terminal and browser windows open at any one time, all spread across multiple space. When I use Control-F3 Mission control displays all the windows for that application regardless of which space they are from. Is there a way to do something similar but only display the windows of the application that are in the current space?
    Thanks!

    You can open Mission Control, which will show your main space at first, and 4-finger swipe right (on Macbook Pro, I don't know the keys without a trackpad) to switch to the next. You will only see the active windows in the other space then.

  • Open file-download window from servlet

    Hi all,
              This is the scenario I'm trying to achieve:
              - Display html page with a button or href "download csv file"
              - the user clicks
              - the file-download pop-up window should appear,so the user can save the
              file at any location
              This is how far I get:
              - when the user clicks a servlet gets activated
              - Servlet:
              - creates the csv file and write it to disk
              - now I want the servlet to do something so that the file-download window
              opens
              - I've tried with forward the request to the url (which only displays the
              content in the browser)
              - I write to HttpServletResponse it opens the file in excel which I don't
              want
              Any ideas ?
              Thanks in advance
              Per
              

    Thanks Mettu,
              that worked fine.
              This is what the code looked like:
              ...Per
              ==========================================================================
              if (nextPage.getType()== Page.TYPE_CSV)
              String filePath = (String) req.getAttribute(Attribute.CSV_FILE_PATH);
              String fileName = (String)
              req.getAttribute(Attribute.CSV_FILE_NAME);
              file://Writing text file like this enforces fileDownload popup
              window
              res.setContentType("application/RFC822");
              res.setHeader("Content-Disposition", "attachment; filename=\"" +
              fileName);
              writeFileToOutStream(res,filePath,fileName);
              private void writeFileToOutStream(HttpServletResponse res,String
              filePath,String fileName) throws IOException
              OutputStream out1 = res.getOutputStream();
              FileInputStream fin = new FileInputStream(filePath + fileName);
              byte [] b = new byte[1024];
              int size = 0;
              while((size = fin.read(b, 0, 1024)) > 0)
              out1.write(b, 0, size);
              fin.close();
              out1.flush();
              out1.close();
              ==========================================================================
              "Mettu Kumar" <[email protected]> wrote in message
              news:[email protected]...
              > Per,
              >
              > For this to work in both Netscape and IE, You need You need to set
              content
              > Type and Also a header information.
              >
              > Set Content Type As : Content-type: application/RFC822
              > set the Header "Content-Disposition" to "attachment; filename=\"" +
              > youfilename + "\""
              > Where youfilename is the name of the file you display to
              user.
              >
              > If you want the exact java code use the following two lines of code in
              your
              > servlet:
              > res.setContentType("Content-type: application/RFC822");
              > res.setHeader("Content-Disposition", "attachment; filename=\"" +
              youfilename
              > + "\"");
              >
              >
              > This should solve your problem.
              >
              >
              > Kumar.
              >
              > Per Lovdinger wrote:
              >
              > > Hi all,
              > >
              > > This is the scenario I'm trying to achieve:
              > >
              > > - Display html page with a button or href "download csv file"
              > > - the user clicks
              > > - the file-download pop-up window should appear,so the user can save
              the
              > > file at any location
              > >
              > > This is how far I get:
              > > - when the user clicks a servlet gets activated
              > > - Servlet:
              > > - creates the csv file and write it to disk
              > > - now I want the servlet to do something so that the file-download
              window
              > > opens
              > >
              > > - I've tried with forward the request to the url (which only displays
              the
              > > content in the browser)
              > > - I write to HttpServletResponse it opens the file in excel which I
              don't
              > > want
              > >
              > > Any ideas ?
              > > Thanks in advance
              > > Per
              >
              

  • In the lower right hand corner of the screen, how do I stop the download window from poping up each time I download something?

    In the lower right hand corner of my screen, everytime I download, a download window pops up, that scans what I downloaded for a virus then gives me a message that says download is complete. How do I disable that feature?.

    To turn off the alert you can change a hidden preference.
    # Type '''about:config''' into the location bar and press enter
    # Accept the warning message that appears, you will be taken to a list of preferences
    # Locate the preference '''browser.download.manager.showAlertOnComplete''' and double-click on it to change its value to '''false'''
    # If you want to stop Firefox requesting a virus scan, double click on the preference '''browser.download.manager.scanWhenDone''' to change its value to '''false'''

  • Download data from jsp to Excel

    Originally, when I was using tomcat as the web server (installed at my local machine), I wrote a jsp which allows users to download Oracle table data to a Excel file. When the user clicks "Download" data, a "File Download" dialog box pops up and asks whether the user want to "Open this file from its current location" or "Save this file to disk". That is what I want.
    Now, I migrate the application to OC4J (installed at Sun Solaris Server), the same program is not working as the same way as above. If the user clicks the link, then the program simply display the jsp page. In order to download data, the user needs to right click the link and selects "Save Target as".
    How to make the application work just like it works on tomcat? Is this a programming issue or a server configuration issue?
    Thanks.
    Jingzhi

    Hi,
    I am having the same exact problem that you had months ago. Would love to hear if you came up with a solution? Original post included below...
    Thanks,
    Andres
    ORIGINAL POST:
    Hi
    I could successfully send the data from a jsp file to a excel file. But, I have a problem with the data. The data i pass is normally alpha numeric, but some times the data is something like '00123456'. In such cases, i am loosing the leading zeros and get '123456'. Is there any way i can get around with this problem?
    Help is greatly appreciated.
    Bharat

  • Displays - gather windows from 2nd monitor? OR - turn off detected display?

    I use my Sony HDTV (960XBR) via HDMI as a 2nd monitor sometimes (also use a 17" LCD sometimes). When not using the Sony for the Mac (like actually watching TV!), the Mac still detects it as a display and allows any program windows I'd placed there to remain on that display, even though it's not actually displaying the Mac signal.
    Question: is there any way to "gather" all program windows onto the primary display? Or "turn off" a detected display from the Mac?
    Thanks!

    Most applications support the following: under the Window menu, you'll see a "Bring All to Front" command. If you hold down the Option key, that changes to "Arrange in Front". Choose that to have all windows arranged in front. That should probably force all windows to the main screen.
    Hope this helps.....
    Dual 2.7GHz PowerPC G5 w/ 2.5 GB RAM; 17" MacBook Pro w/ 2 GB RAM -   Mac OS X (10.4.6)  

  • Display excel file from jsp

    hi i am trying to read an excel file from a location on the app server and display it in the browser (ie). the excel file should open up and not display the open/save dialog.
    following is the code that i am using. i am not able to get it to work. getting an illegalstateexception and also i am getting all garbage diplayed in the browser. no excel. kindly help.
    <%@ page import="java.io.*" contentType="application/vnd.ms-excel"%>
    <%@ taglib uri="/WEB-INF/tlds/sapphire.tld" prefix="sapphire" %>
    <%@ taglib uri="/WEB-INF/tlds/c.tld" prefix="c" %>
    <%
    //response.reset();
    //response.setHeader("Pragma", "no-cache");
    //response.setHeader("Cache-Control", "no-cache");
    //response.setDateHeader("Expires", 0L);
    ServletOutputStream so = response.getOutputStream();
    String filename = "C:\\example1.xls";
    String mimetype = "application/vnd.ms-excel";
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    InputStream in = new BufferedInputStream(new FileInputStream(filename));
    byte bytebuff[] = new byte[500];
    for(int lengthread = 0; (lengthread = in.read(bytebuff)) != -1;){
    output.write(bytebuff, 0, lengthread);
    byte data[] = output.toByteArray();
    response.setContentType(mimetype);
    so.write(data);
    in.close();
    so.close();
    %>

    A JSP calls getWriter() by default.
    Every time you have a carriage return outside <% %> it gets written to the writer.
    The Illegal state exception would be because you are getting the outputStream after the writer.
    This is better done in a servlet, but can be done in a JSP, try it with code like this:
    <%@ page import="java.io.*" contentType="application/vnd.ms-excel"
    %><%@ taglib uri="/WEB-INF/tlds/sapphire.tld" prefix="sapphire"
    %><%@ taglib uri="/WEB-INF/tlds/c.tld" prefix="c"
    %><%
    %> Note that there is no text at all outside of the <% %> (not even carriage returns)
    Also, why are you writing to a ByteArrayOutputStream (ie into a memory byte array), and then writing the byte array to the servletoutputstream?
    Just put a buffer around the servlet outputstream and write directly to that.
    ServletOutputStream so = response.getOutputStream();
    BufferedOutputStream output = new ByteArrayOutputStream(so);
    ...

  • Open alert-ish window from jsp?

    Hi, I'm trying to find a way to alert the user of my jsp that he entered non-valid chars in my inputfields. Usually I'd do this in the js-validation of the input on submit but I was wondering if I could get the jsp to do something like it on submit? I mean, in stead of out.println, then out.println in a new window? I know it's rather circumstantial but I got curious :)
    My reason for not doing it in js is that I have a try catch validating if my entered string is an int. I know it's doable in js too but hey.. can't blame a girl for trying something new, right? :)

    JSP is all server side so you would have to post your form to your servlet and have it validate and then redisplay the form to the user if they entered something bad.
    Best bet is to do your validation with js and use alert boxes.
    -S-

  • Display an attachment from jsp

    Hello,
    I store my web application attachments under ROOT folder and my problem is that I can access to them also if I write directly the appropiate url in the browser without entering in the application...
    How should I do to access to files only through a servlert which authenticate the user and not directly from url?
    Thanks
    T

    Any idea?
    Thanks
    T

  • Path and file name problem when I want to download files from html

    Hi all,
    I want to write a small program to allow users download files from jsp file
    but the following files don't work .
    <%@ page language="java" import="java.net.*,java.io.*"%>
    <%@ page import ="java.util.*"%>
    <%
    try
    String SContent = request.getParameter("click");
    String SDocName = "temp.doc"; //  out put file File Name
    ServletOutputStream stream= response.getOutputStream(); // Getting ServletOutputStream
    response.setContentType("application/msword"); // Setting content type
    response.setHeader("Content-disposition","attachment;filename=\"" +SDocName+"\""); // To pop dialog box
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(SContent));
    int c;
    while ((c = in.read()) != -1){
               stream.write(c);
    in.close();
    stream.flush();
    catch(final IOException e)
    System.out.println ( "IOException." );
    catch(Exception e1)
    System.out.println ( "Exception." );
    %>I am so confuse, what is the path and file name I sould give ? for example my click should equal to http://******/Test/display.jsp?click=00-1

    Hi all,
    I got error at
    java.lang.IllegalStateException: getOutputStream() has already been called for this response
         org.apache.coyote.tomcat5.CoyoteResponse.getWriter(CoyoteResponse.java:599)
    if I want ot download file from html file.
    String SContent = request.getParameter("click");
    if I hard code like follow it work fine.
    String SContent ="C:/Project Coding.doc";
    what mistake I make.
    Thank you!

  • Weird characters displayed after Windows update

    A user encountered this issue after a Windows update.
    https://twitter.com/summerscope/status/414887724131168256/photo/1
    Did anyone encounter this too, and what did you do?
    Thanks in advance.
    serene
    Community Advocate Program Manager
    English Community   Deutsche Community   Comunidad en Español   Русскоязычное Сообщество

    Hi John,
    >
    <Location /pls/nxdev>
    Order deny,allow
    PlsqlDocumentPath docs
    AllowOverride None
    PlsqlDocumentProcedure wwv_flow_file_manager.process_download
    PlsqlDatabaseConnectString hostname:1521:... ServiceNameFormat
    PlsqlNLSLanguage NORWEGIAN_NORWAY.AL32UTF8
    PlsqlAuthenticationMode Basic
    SetHandler pls_handler
    PlsqlDocumentTablename wwv_flow_file_objects$
    PlsqlDatabaseUsername APEX_PUBLIC_USER
    PlsqlDefaultPage apex
    PlsqlDatabasePassword pass
    Allow from all
    </Location>>
    >
    CREATE OR REPLACE procedure schema.dl_file (p_fileid in number)
    as
    l_mime varchar2(255);
    l_length number;
    l_filename varchar2(2000);
    lob_loc BLOB;
    begin
    select col1,col2,col3,col4 into l_filename, l_length, l_mime, lob_loc from km_docs where kmd_id = p_fileid;
    -- Set up HTTP header
    -- Use an NVL around the mime type and if it is a null, set it to
    -- application/octect - which may launch a download window from windows
    owa_util.mime_header(nvl(l_mime,'application/octet'), FALSE );
    -- Set the size so the browser knows how much to download
    htp.p('Content-length: ' || l_length);
    -- The filename will be used by the browser if the users does a "Save as"
    htp.p('Content-Disposition: filename="' || l_filename || '"');
    -- Close the headers
    owa_util.http_header_close;
    -- Download the BLOB
    wpg_docload.download_file( Lob_loc );
    end;
    >
    Thanks!
    PS: Some updates...I tried it in IE as well (I use FF when working with applications) and funny enough the photos and documents get displayed/the download box shows up.
    But, all the files have the name f. f.pdf, f.jpeg etc
    I tried calling the dl_image procedure in the url (currently I call a new page where I pass the file id to an application id and then I call the above procedure in a pl/sql block):
    http://www.host/pls/dad/schema.dl_file?p_fileid=1
    And the name seems ok. I don't think it's a good idea to put the procedure name in the link, is it?
    Edited by: AndreaC on Nov 18, 2008 3:30 PM

  • Is there a way to display movies purchased from itunes from my ipad to my apple TV without internet (still using wifi)

    I am going on vacation and will have a wifi network, but no internet access. I have tried to display downloaded movies from my ipad purchased on itunes to my apple TV, but get "Unknown Error -3". I can use mirroring, but not show the video. I am signed into the same account on both devices and the movie is downloaded to the ipad. The only issue I can think of is some DRM check, but I am not sure.
    Has anyone been able to do this? It would be nice to be able to use my purchased movies on vacation without needing internet.
    thanks for any help

    DBK@apple wrote:
    Is there anyway that you know of to utilize iTunes purchased content that has been downloaded to a device on a TV without internet? This really limits when it can be used on vacation or when internet is down etc.
    Will the lightning to HDMI dongle work?
    thanks for any help!
    This was a big advantage of AppleTV1 - generally it did not need internet authorisation for synced material on its internal drive and was great for holiday/vacation.
    I tend to use a Mac Mini these days when going away.

  • Downloading files from database in Google Chrome and Firefox

    I am using a modified version of  the get_doc to view files stored in the database.  I am able to use this code perfectly in Internet Explorer but attempting view the data in Firefox or Google Chrome opens up a page showing the data in a binary format.  I believe it may have something to do with the headers.  The code is as follows:
    create or replace
    package body          "PKG_FILES" is
    PROCEDURE pr_open_file(p_table in varchar2, p_id in number, p_name in varchar2 DEFAULT null, p_content in varchar2 DEFAULT 'CONTENT') AS
         v_query        VARCHAR2(1000);
         v_mime         VARCHAR2(48);
         v_length       NUMBER;
         v_file_name    VARCHAR2(2000);
         v_table        VARCHAR2(100);
         Lob_loc        BLOB;
    BEGIN
      v_table := p_table;
      v_query := 'SELECT MIME_TYPE,'|| p_content ||', FILE_NAME, DBMS_LOB.GETLENGTH('||p_content||') FROM '||v_table ||' WHERE '||v_table||'_ID = :id';
      EXECUTE IMMEDIATE v_query INTO v_mime,lob_loc,v_file_name,v_length USING p_id;
                  -- set up HTTP header
                        -- use an NVL around the mime type and
                        -- if it is a null set it to application/octect
                        -- application/octect may launch a download window from windows
                        owa_util.mime_header( nvl(v_mime,'application/octet'), FALSE );
                    -- set the size so the browser knows how much to download
                    htp.p('Content-length: ' || v_length);
                    -- the filename will be used by the browser if the users does a save as
                    htp.p('Content-Disposition:  attachment; filename="'||replace(replace(substr(v_file_name,instr(v_file_name,'/')+1),chr(10),null),chr(13),null)|| '"');
                    -- close the headers           
                    owa_util.http_header_close;
                    -- download the BLOB
                    wpg_docload.download_file( Lob_loc );
    end pr_open_file;
    end "PKG_FILES";
    Has anyone had this same issue or any ideas?

    Before Little Bobby Tables logs into your application, make sure you read up on DBMS_ASSERT to ensure that the table name and column are valid DB objects before you dynamically create any SQL statements.
    ie prevent SQL Injection.
    Other than that, use APEX_DEBUG.MESSAGE() to spit out some information... like which MIME/TYPE you are using.
    It could be that the value stored in the database table is invalid.
    hint:  the ORDDoc data type could be used to detect the correct mime/type.
    Finally, I've read somewhere that an APEX_APPLICATION.STOP_APEX_ENGINE() was needed at the very end of the process.
    MK

Maybe you are looking for