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

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"

  • 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());

  • 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);
    ...

  • Display multiple Images from a DB on a JSP Page!

    Hi all, please give me your solution, thanks. I have many images, stored in Oracle database (BLOB), How to display all of them (images) on a JSP page? I have a working solution that only shows one image based on the specific image-name passed. But if no image found in the Database with that image-name then I want to show all the images at once on a JSP page. Can someone help please. Follwing are the code snippets:
    Here is the JSP page that calls the servlet to show the images:
    <%@ page contentType="text/html;charset=windows-1252"%>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
        <title>untitled</title>
      </head>
      <body valign=center>
          <table>
            <tr>
                <td>
                    <img src="/test-testimgs-context-root/servlet/test1.images.servlet.GetImage">
                </td>
            </tr>
          </table>
      </body>
    </html>
    Here is the code that resides in the service method of GetImage servlet:
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
        OutputStream stream = response.getOutputStream(); 
        Blob imgBlob = null;
        ResultSet rs = null;
        byte[] imbBytesAry = null;
        try
            ImageTest imgtest = new ImageTest();
            rs = imgtest.get("img1.tif");
            if(rs != null)
                while(rs.next())
                    imgBlob = rs.getBlob(1);
                    int len = new Integer( new Long( imgBlob.length()).toString() ).intValue();
                    imbBytesAry = imgBlob.getBytes(1,len);
                    if (imbBytesAry.length == 0 || imbBytesAry == null)
                        noImageFound(request, response); 
                    else
                        stream.write(imbBytesAry);
            else
                noImageFound(request, response);
        catch (Exception e)
            noImageFound(request, response);
    Here is the code that resides in the get method of ImageTest class:
    public ResultSet get(String fileName) throws DatabaseConnectionException, SQLException, Exception
    Connection connection=null;
    ResultSet rs = null;
    ResultSet rs1 = null;
    Blob imgBlob = null;
    try
        connection = new ConnectionProvider().getCConnection() ;
        connection.setAutoCommit(false);
        Statement stmt = connection.createStatement();
        String sql = "SELECT IMG FROM IMAGE_TABLE WHERE IMAGE_NAME = ? "; 
        PreparedStatement pstmt = connection.prepareStatement(sql);
        pstmt.setString(1,fileName);
        rs = pstmt.executeQuery();
        boolean flag = rs.next();
        if(flag)
            rs.beforeFirst();
        else
            sql = "SELECT IMG FROM IMAGE_TABLE"; 
            rs1 = stmt.executeQuery(sql);
            boolean flag_all = rs1.next();
            if(flag_all)
                rs1.beforeFirst();
            else
                rs1 = null;
        return rs;
    }As you see in the JSP page I am calling GetImage servlet, whose service method does all the processing i.e. calls ImageTest get method that queries the database and returns the result. Eventually what I would like is to pass the filename along with other parameters from JSP page and the servlet returns the images based on that. Currently I have just hard coded a value for testing puposes. Any help is appreciated.
    Thanks

    Hi all, please give me your solution, thanks. I have many images, stored in Oracle database (BLOB), How to display all of them (images) on a JSP page? I have a working solution that only shows one image based on the specific image-name passed. But if no image found in the Database with that image-name then I want to show all the images at once on a JSP page. Can someone help please.
    this is the code
    <form name="a" action="" method="post">
    <%
    rs1 = st1.executeQuery(select1);
    rs1.next();
    while(rs1.next())
    %>
    <table>
    <tr><td>
    <%
    Blob objBlob[] = new Blob[rs1.getMetaData().getColumnCount()];
         for (int i = 0; i <= rs1.getMetaData().getColumnCount(); i++)
               objBlob[i] = ((OracleResultSet)rs1).getBLOB(1);
              InputStream is = objBlob.getBinaryStream();
    byte[] bytearray = new byte[4096];
    int size=0;
    response.reset();
    response.setContentType("image/jpeg");
    response.addHeader("Content-Disposition","filename=getimage.jpeg");
    while((size=is.read(bytearray))!= -1 )
    response.getOutputStream().write(bytearray,0,size);
    response.flushBuffer();
    is.close();
    out.println("hhhhhhh");
    %>
    </table>
    <%
    rs1.close();
    //con.close();
    %>
    </form>

  • Sending attachment from servlet or jsp

    Dear Friends,
    I downloaded javamail api and I have seen the sendfile.java, which is used to send attachments. it is working fine. I can able to run that program from command prompt like this :=
    c:>java sendfile [email protected] [email protected] mail.smtp.net c:/hello.java true
    It is working fine from console (command prompt)
    How can i execute that file on browser (i have to run as a servlet file or from jsp file).
    please help me how can i pass the emailids, file etc., if i want to use this program as servlet file or as jsp program.
    If anyone having idea, please share ur ideas.
    your kind cooperation would be greatly appreciated.
    Thanks in advance.
    Looking forward to hearing from you.
    Yours
    Rajesh
    ==
    program is like this (which is in javamail home ..demo directory
    ==
    import java.util.*;
    import java.io.*;
    import javax.mail.*;
    import javax.mail.internet.*;
    import javax.activation.*;
    * sendfile will create a multipart message with the second
    * block of the message being the given file.<p>
    * This demonstrates how to use the FileDataSource to send
    * a file via mail.<p>
    * usage: <code>java sendfile <i>to from smtp file true|false</i></code>
    * where <i>to</i> and <i>from</i> are the destination and
    * origin email addresses, respectively, and <i>smtp</i>
    * is the hostname of the machine that has smtp server
    * running. <i>file</i> is the file to send. The next parameter
    * either turns on or turns off debugging during sending.
    * @author     Christopher Cotton
    public class sendfile {
    public static void main(String[] args) {
         if (args.length != 5) {
         System.out.println("usage: java sendfile <to> <from> <smtp> <file> true|false");
         System.exit(1);
         String to = args[0];
         String from = args[1];
         String host = args[2];
         String filename = args[3];
         boolean debug = Boolean.valueOf(args[4]).booleanValue();
         String msgText1 = "Sending a file.\n";
         String subject = "Sending a file";
         // create some properties and get the default Session
         Properties props = System.getProperties();
         props.put("mail.smtp.host", host);
         Session session = Session.getDefaultInstance(props, null);
         session.setDebug(debug);
         try {
         // create a message
         MimeMessage msg = new MimeMessage(session);
         msg.setFrom(new InternetAddress(from));
         InternetAddress[] address = {new InternetAddress(to)};
         msg.setRecipients(Message.RecipientType.TO, address);
         msg.setSubject(subject);
         // create and fill the first message part
         MimeBodyPart mbp1 = new MimeBodyPart();
         mbp1.setText(msgText1);
         // create the second message part
         MimeBodyPart mbp2 = new MimeBodyPart();
    // attach the file to the message
         FileDataSource fds = new FileDataSource(filename);
         mbp2.setDataHandler(new DataHandler(fds));
         mbp2.setFileName(fds.getName());
         // create the Multipart and its parts to it
         Multipart mp = new MimeMultipart();
         mp.addBodyPart(mbp1);
         mp.addBodyPart(mbp2);
         // add the Multipart to the message
         msg.setContent(mp);
         // set the Date: header
         msg.setSentDate(new Date());
         // send the message
         Transport.send(msg);
         } catch (MessagingException mex) {
         mex.printStackTrace();
         Exception ex = null;
         if ((ex = mex.getNextException()) != null) {
              ex.printStackTrace();

    Hi,
    your sendmail.jsp would look like that:
    <%@ page import="java.util.*,java.io.*,javax.mail.*,javax.mail.internet.*,javax.activation.*" %>
    <%
    String to = request.getParameterValues("to")[0];
    String from = request.getParameterValues("from")[0];
    String host = request.getParameterValues("host")[0];
    String filename = request.getParameterValues("filename")[0];
    String msgText1 = "Sending a file.\n";
    String subject = "Sending a file";
    // create some properties and get the default Session
    Properties props = System.getProperties();
    props.put("mail.smtp.host", host);
    Session session = Session.getDefaultInstance(props, null);
    session.setDebug(debug);
    try {
    // create a message
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(from));
    InternetAddress[] address = {new InternetAddress(to)};
    msg.setRecipients(Message.RecipientType.TO, address);
    msg.setSubject(subject);
    // create and fill the first message part
    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(msgText1);
    // create the second message part
    MimeBodyPart mbp2 = new MimeBodyPart();
    // attach the file to the message
    FileDataSource fds = new FileDataSource(filename);
    mbp2.setDataHandler(new DataHandler(fds));
    mbp2.setFileName(fds.getName());
    // create the Multipart and its parts to it
    Multipart mp = new MimeMultipart();
    mp.addBodyPart(mbp1);
    mp.addBodyPart(mbp2);
    // add the Multipart to the message
    msg.setContent(mp);
    // set the Date: header
    msg.setSentDate(new Date());
    // send the message
    Transport.send(msg);
    } catch (MessagingException mex) {
    mex.printStackTrace();
    Exception ex = null;
    if ((ex = mex.getNextException()) != null) {
    ex.printStackTrace();
    %>
    which you can call as: sendmail.jsp?to=...&from=...&host=...&filename=...
    so you may need to create a HTML file containing the necessary form.

  • How do I Display a string from a servlet into a JSP Page???? NEED HELP!!!!

    Hi guys,
    How do I Display a string from a servlet into a JSP Page...
    Ive tried so many bloody things!.....
    Simply.
    I get text from JSP. The servlet does what ever it does to the string.
    Now. Ive create sessions and bean things,.... how the hell do I display it in a text box... I can display on the screen.. but not in the text box.!!!
    please help!!!

    hmmm, I dont really like using JSP programming, u should be using JAVA..
    the way to do it is:
    Call and cast to the bean like this:
    <%@ page import="beans.*" %>
    <% //cast to bean get request create object
    userNameBean u= (userNameBean) request.getSession().getAttribute("userNameBean");
    then... all you do is call it like this:
    <input type="text" name="firstName" value="<%= u != null? u.getFirstName(): "" %>">
    this is the real programmers way,,,
    chet.~

  • Can i display all images from databases with adf jsp

    hi
    I want to display all images from the databases whit adf bussines components, because with the sample on http://www.oracle.com/technology/training/products/intermedia/index.html page, i only can display 10 images. i'd lije to know if i can to search in the databases by the id of the image.
    this is the code:
    %@ taglib uri="http://xmlns.oracle.com/adf/ui/jsp/adftags" prefix="adf"%>
    <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
    <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
    <%@ page contentType="text/html;charset=windows-1252"%>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <title>untitled</title>
    </head>
    <body>
    <html:errors/>
    <table border="1" width="100%">
    <tr>
    <th> </th>
    <th>
    <c:out value="${bindings.ImagenView1.labels['Id']}"/>
    </th>
    <th>
    <c:out value="${bindings.ImagenView1.labels['Descripcion']}"/>
    </th>
    <th>
    <c:out value="${bindings.ImagenView1.labels['Image']}"/>
    </th>
    </tr>
    <c:forEach var="Row" items="${bindings.ImagenView1.rangeSet}">
    <tr>
    <td>
    <c:out value="${Row.currencyString}"/>
    </td>
    <td>
    <c:out value="${Row['Id']}"/> 
    </td>
    <td>
    <adf:render model="Row.Image"/>
    </td>
    <td>
    <c:out value="${Row['Image']}"/> 
    </td>
    </tr>
    </c:forEach>
    </table>
    </body>
    </html>

    I think you want the interMedia JSP tag library...
    http://www.oracle.com/technology/software/products/intermedia/htdocs/descriptions/tag_library.html
    Larry

  • When i go to attach a photo to email or load it to facebook it will not display any photos from my iphoto library and only allows me load ones that are in photo booth or saved on the desktop. Any ideas?

    when i go to attach a photo to email or load it to facebook it will not display any photos from my iphoto library and only allows me load ones that are in photo booth or saved on the desktop. Any ideas what is wrong?

    when i go to attach a photo to email or load it to facebook it will not display any photos from my iphoto library and only allows me load ones that are in photo booth or saved on the desktop. Any ideas what is wrong?

  • How To Display JasperReport From JSP ????

    Hi All ;
    I am new user for JasperReport ;
    Please Help ME :::
    How Can I Display JasperReport From JSP ????
    Regards;

    BalusC wrote:
    Follow those steps to get a listing of useful links how to learn JasperReport:
    1) Go to http://www.google.com, you'll see one input field and one button.
    2) Enter "jasperreport tutorial" in that input field.
    3) Hit the button next to that input field.and don't forget to pose this question @ http://jasperforge.org as that would be a better place where you can get better replies as people their specialize on the solution offered by jasper soft such as Reporting,BI and blah blah blah.
    and for the time being hope the below thread might give you a basic start if you have basic understanding of how Jasper Reporting works.
    http://forum.java.sun.com/thread.jspa?threadID=5203324&messageID=9811077
    http://forum.java.sun.com/thread.jspa?threadID=5212278
    Hope there are no hard issues on this,as it is just to point you to the right direction :)
    REGARDS,
    RaHuL

  • Sending mail from JSP page with attachment

    I have a requirement to send mail with attachment from my jsp pages, which should come to a particular mail box. Can any one help me by sending sample codes. Thankx in advance.

    hi,
    When request is posted you have to save file data from request to a file. you can not access the data using request.getParameter("file").

  • Unable to open URL attachment from SBWP in CRM WEB UI

    Hello Gurus,
    Need your help please. I'm having some problem opening the URL attachment from SBWP via CRM 7 WEB UI (I used a Transaction Launcher for SBWP). The attachment is a Webdynpro application.  I am able to open the attachment in SAP GUI, but not in CRM WEBUI. This problem occured when we update the SP level of CRM 7.
    Here's the scenario,
    - whenever I click the attachment, it open a new window, which also happen even before SP level update, with the following information:
      Execute an Application on FrontEnd
      Please wait. You will be forwarded automatically.
      This page is included for technical reason.
      Execute program.
      Status: Displaying Office Document ..........
      After a couple of seconds, it will return to the Workflow Workplace screen.
    I have checked the workflow log and found no inconsistency on the attached URL.
    Immediate response would be highly appreciated. Thanks in advance.
    Regards,
    Edwin

    Thanks for the reply WD ABAP.
    Yes, I did try to use the functionality of Worklist and the URL attachment successfully opened. However, there are some limitation in its functionality as indicated in the link below that opted us to use the SBWP in CRM WEB UI via transaction launcher.
    http://wiki.sdn.sap.com/wiki/display/CRM/CRMWorklist-AdvancewithDialognotSupported
    We don't want to adjust the logic of our existing workflow at this point as described in the above link as it will entails end-to-end testing again. We just encountered this issue when we update the SP level of CRM 7.
    Hope there is an alternative solution without shifting us to Worklist.
    Regards,
    Edwin

  • Accessing JSTL values from JSP

    I've run into a problem I'm not sure has a solution. Could be bad design on my part, or just a poor imagination. If this has been answered previously, please point me to the post.
    I am using some JSTL to do a SQL query and displaying the records in a select box:
    <sql:query var="aResults" sql="select * from TYPE_STATE_LIST where tslAllowable=1" />                           
    <c:forEach var="oRecord" items="${aResults.rows}">                               
      <option value="<c:out value="${oRecord.tslID}" />"><c:out value="${oRecord.tslFullName}" /></option>                                   
    </c:forEach>I want to be able to reset their selection to the value they entered when the form is refreshed, though. I'm trying to figure out how to grab the oRecord value from the JSTL and use it in a JSP IF statement:
    <% if( oRecord.tslID==request.getParameter("state") ) { %>
      <option selected value="<c:out value="${oRecord.tslID}" />"><c:out value="${oRecord.tslFullName}" /></option> 
    <% } else { %>
      <option value="<c:out value="${oRecord.tslID}" />"><c:out value="${oRecord.tslFullName}" /></option> 
    <% } %>I thought about using the JSTL <c:choose> tag instead, but then how would I access the previous value with request.getParameter()?
    Any suggestions?

    ${param.state}It's better if you place the sql query into a class rather than display it in the jsp, it's more flexible and programmable.

  • Problem with displaying BLOB images on JSP page using a servlet

    hi. I have a big problem with displaying BLOB images using JSP. I have a servlet that connects to the oracle database, gets a BLOB image , reads it, and then displays it using a BinaryStream. The problem is , this works only when i directly call that servlet, that is http://localhost:8080/ImageServlet. It doesn't work when i try to use that servlet to display my image on my JSP page (my JSP page displays only a broken-image icon ) I tried several coding approaches with my servlet (used both Blob and BLOB objects), and they work just fine as long as i display images explicitly using only the servlet.
    Here's what i use : ORACLE 10g XE , Eclipse 3.1.2, Tomcat 5.5.16 , JDK 1.5
    here is one of my image servlet's working versions (the essential part of it) :
                   BLOB blob=null;
              rset=st.executeQuery("SELECT * FROM IMAGES WHERE ID=1");
              while (rset.next())
                   blob=((OracleResultSet)rset).getBLOB(2);
              response.reset();
              response.setContentType("image/jpeg");
              response.addHeader("Content-Disposition","filename=42.jpeg");
                    ServletOutputStream ostr=response.getOutputStream();
                   InputStream istr=blob.getBinaryStream(1L);
                    int size=blob.getBufferSize();
              int len=-1;
                    byte[] buff = new byte[size];
                         while ((len=istr.read( buff ))!=-1 ) {
                   ostr.write(buff,0,len);
             response.flushBuffer();
             ostr.close(); and my JSP page code :
    <img src="/ImageServlet" border="0"  > If you could just tell me what i'm doing wrong here , or if you could show me your own solutions to that problem , i would be very greatful ,cos i'm realy stuck here , and i'm rather pressed for time too. Hope someone can help.

    I turns out that it wasn't that big of a problem after all. All i had to do was to take the above code and place it into another JSP page instead of into a servlet like i did before. Then i just used that page as a source for my IMG tag in my first JSP. It works perfectly well. Why this doesn't work for servlets i still don't know, but it's not a problem form me anymore . Ofcourse if someone knows the answer , go ahead and write. I would still appriceatte it.
    here's the magic tag : <img src="ImageJSP.jsp" border="0"  > enjoy : )

  • Display Image in another jsp

    hello,
    I am facing a design issue of so as to how to go about displaying an image which i am retrieving from database.
    I have a SubmitDoc.jsp which takes as input the doc id which i need to display looks like :
    *SubmitDoc.jsp*
    <FORM METHOD=POST ACTION="Retrieval">
    Enter Document ID to Retrieve: <INPUT TYPE=TEXT NAME=DOCID SIZE=20/><BR>
    <P><INPUT TYPE=SUBMIT></P>
    </FORM>I have my Retrieval servlet which access the DB and gets the binary stream for the image data based on DOCID.
    Now i try to forward result to a different jsp in order to display the binary data from the servlet.
    something like this :
    InputStream readImg = rs.getBinaryStream("DOCUMENT");
    response.setContentType("image/jpg");
    request.setAttribute("ImageData", readImg);
    // response.getOutputStream().write(rb,0,len);
    RequestDispatcher rd = request.getRequestDispatcher("DisplayDoc.jsp");
    rd.forward( request, response );What code should i put in DisplayDoc.jsp to show the image there.
    Any ideas how do i go about ?
    Thanks,

    What code should i put in DisplayDoc.jsp to show the image there.The same code you put in any html page to show an image:
    <img src="urlToDownloadImageFrom"/>In effect you have two requests.
    One for the JSP page, and then another for the image.
    So often what you find is the tag on your page needs to pass the id as well
    <img src="/ImageServlet?docId=abc123"/>

Maybe you are looking for