Link to home
Start Free TrialLog in
Avatar of vamshicheruku
vamshicheruku

asked on

how to specify relative path in jsp

hi all,

i want the client to download a file from server side

here is my directiory structure

                  WebRegistration
                          /        \
                         /          \
                        /            \
                      jsp           WEB-INF
                      /              \
                     /                \
                    /                  \
               localreg             classes
                                      /  
                                     /
                                 registration  
                                  /
                                 /
                              files

my jsp's are in left "localreg" folder  and my java programs are in "registration" folder and the file which client should download is in "files" folder

here is the jsp which i am using to make client download the file

String filename ="download.ash";(this is in "files"folder)
String filepath =
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
out.flush();
java.io.FileInputStream fileInputStream =new java.io.FileInputStream(filepath+"/"+filename);
int i=0;
while ((i=fileInputStream.read())!= -1)
{
     out.write(i);
}
fileInputStream.close();
out.flush();
out.close();

what i want to know is how should i write "filepath"(in the porgram) relatively.

thanks in advance

regards,
vamshi

Avatar of pat5
pat5

i think your path should have this in <a>
<a href="../WEB-INF/classes/registration/files/somefilename.ext"></a>
hope this will help u.
ASKER CERTIFIED SOLUTION
Avatar of cheekycj
cheekycj
Flag of United States of America 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
anything under web-inf is not directly accessable by client. put your files in other dir, e.g. WebRegistration/file
Avatar of vamshicheruku

ASKER

hi cheekycj,

i did not get you but, i would be happy if you were more specific i.e modify my code and write it again..

and one more thing for "kennethxu" when i give the absolute path like

filepath="c:\tomcat\webapps\WebRegistration\WEB-INF\classes\localreg\files"
it works..
i want to make it relative because when ever i take the "webregistration" folder to othere place i should not change anything
that is the reason i want to use relative path

regards,
vamshi
String filename ="download.ash";(this is in "files"folder)
String filepath = "/WEB-INF/classes/registration/files"
java.io.OutputStream outStream =  response.getOutputStream();
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
java.io.InputStream in = application.getResourceAsStream(filepath+"/"+filename);
int i=0;
while ((i=in.read())!= -1)
{
    outStream.write(i);
}
in.close();
outStream.flush();
outStream.close();
above code is to illustrate the idea. it's not tested and has syntax error. i think you can sort it out but let me know if you have furter queries
this is not working kennethxu
In that case:

use getAbsolutePath() method. like,

if this works:
filepath="c:\tomcat\webapps\WebRegistration\WEB-INF\classes\localreg\files"

than use this:

File file = new File("");
String fullPath = file.getAbsolutePath()+"\\WebRegistration\\WEB-INF\\classes\\localreg\\files";

Note: if your file structure is not going to change from
\WebRegistration\WEB-INF\classes\localreg\files

if want to deploy on UNIX ENV. use like this:

String fullPath = file.getAbsolutePath()+"//WebRegistration//WEB-INF//classes//localreg//files";

if you use this it will work for both ENV. WINDOWS & UNIX.

where ever you deploy your application, you will get

c:\tomcat\webapps\ + your file structure which is never going to change.
if UNIX YOU WILL GET:
/tomcat/webapps/ + your hard coded path.



>> this is not working kennethxu
what error message did you get?
actually, jsp is not so good for this purpose, I would use servlet:

package mypackage;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public final class DownloadServlet extends HttpServlet {
    private static final String filepath = "/WEB-INF/classes/registration/files";

   public void service(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, java.io.IOException
    {
         String pathInfo = request.getPathInfo();
         if( pathInfo != null && pathInof.indexOf("..") < 0 ) {
            InputStream in = getServletContext().getResourceAsStream(filepath + pathInfo);
            
            if( in != null ) {
                      OutputStream out = new BufferedOutputStream( response.getOutputStream() );
                      in = new BufferedInputStream( in );
                      response.setContentType( "application/octet-stream" );
                      response.setContentLength( (int) file.length() );
                        int c;
                        while( ( c=in.read() ) != -1 ) out.write( c );
                        in.close();
                        out.close();
                        return;
                   }
              }
         }
         response.sendError( HttpServletResponse.SC_NOT_FOUND );
    }
}

let's say map your servlet to /download/*, then user can access the file as
http://www.server.com/context/download/download.ash
hi kennethxu, pat5 and cheekycj,

 you guys have been great help for me..i was cleared with the relative path and one more doubt
this is the modified program

//"good" is a variable for changing filename
filename=good+".upr";File file=new File("");
filepath=file.getAbsolutePath()+"/"+"files";
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
out.flush();
java.io.FileInputStream fileInputStream =new java.io.FileInputStream(filepath+"/"+filename);
int i=0;
while ((i=fileInputStream.read())!= -1)
{
    out.write(i);
}
fileInputStream.close();
out.flush();
out.close();

everything is working fine but, the problem is when client clicks on download file, he will be shown a window in which he is given 2 options to open the file or save it to a perticular location
after client chooses an option to save it to a perticular location , then a window opens and he should the name of file by which he wants to save and the type of the file
here my file type is ".upr" but by default the clients window is set to "all files" so he will be saving the file as "good.upr" ...but the problem is if the default save type is text then the file saved will be "good.upr.txt" ...i dont want this
because my program after downloading the file should work on the file downloaded it will not recognise the file if it is of different type than ".upr"  
hope you understood my problem
and i want to know if there is possibility of knowing the
place where the client saved the file after downloading..
it would be of great help if you guys can help me..

thanks in advance

regards,
vamshi
that unfortunately is a side effect of IE.

I haven't found a way around that yet.  if you mess with content type it may screw up the save as dialog prompt.
>> then the file saved will be "good.upr.txt"
this is IE bug (or you call it feature?), try this:

    response.setContentType( "application/force-download" );

>> and i want to know if there is possibility of knowing the place where the client saved the file after downloading..

No way, unless you use signed applet or activeX, the way more complex.
try out this servlet, i found some time tested it so works with IE and NS:

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public final class DownloadServlet extends HttpServlet {
     private static final String basePath = "/WEB-INF/classes/registration/files";

     public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException
     {
        String filePath = request.getPathInfo();
        String filename = request.getParameter( "filename" );
          if( filePath == null && filename != null ) filePath = "/" + filename;
          if( filename == null && filePath != null ) filename = (new File(filePath)).getName();
          else filename = (new File(filename)).getName();

        if( filePath != null ) {
               InputStream in = null;
               OutputStream out = null;
               try {
                    in = getServletContext().getResourceAsStream(basePath + filePath);
                    if( in != null ) {
                    out = new BufferedOutputStream( response.getOutputStream() );
                    in = new BufferedInputStream( in );
                    response.setContentType( "application/unknow" );
                         response.setHeader("Content-Disposition","attachment; filename=\"" + filename + ".upr\"");
                    int c; while( ( c=in.read() ) != -1 ) out.write( c );
                    return;
                    }
               } finally {
                    if( in != null ) try { in.close(); } catch( Exception e ) {}
                    if( out != null ) try { out.close(); } catch( Exception e ) {}
               }
          }
          response.sendError( HttpServletResponse.SC_NOT_FOUND );
     }
}
hi kenneth,

i think your code may help me but the problem is i am not able to understand your code..if you can make me clear regarding that...or i will be familiar if you write this in jsp

regards,
vamshi


hi kenneth,

i think your code may help me but the problem is i am not able to understand your code..if you can make me clear regarding that...or i will be familiar if you write this in jsp

regards,
vamshi


vamshicheruku, the out object of jsp page is a Writer Object, it converts your byte according to the character-encoding of your jsp page. So, when you download binary file, like doc, pdf, the file will be damaged.

usually, file download is best achieved by a servlet.

create a DownloadServlet.java file and compile it with:
javac -classpath c:\tomcat\common\lib\servlet.jar -d c:\tomcat\webapps\WebRegistration\WEB-INF\classes DownloadServlet.java

edit WEB-INF\web.xml file to add:
  <servlet>
    <servlet-name>downloadservlet</servlet-name>
    <servlet-class>DownloadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
       <servlet-name>downloadservlet</servlet-name>
     <url-pattern>/download/*</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
       <servlet-name>downloadservlet</servlet-name>
     <url-pattern>/download</url-pattern>
  </servlet-mapping>

if you have other servlet declared in web.xml file, make sure put all <servlet> tags first, then <servlet-mapping> tags.

restart you server.

access file via:

http://localhost:8080/WebRegistration/download/myfile.ext

or

http://localhost:8080/WebRegistration/download?filename=myfile.ext
hi kenneth,

i think your code may help me but the problem is i am not able to understand your code..if you can make me clear regarding that...or i will be familiar if you write this in jsp

regards,
vamshi


hi kenneth,

I am trying your approach ,,,i will let you know if i get success in this

regards,
vamshi
let me know if you need help trying it out :)
Avatar of girionis
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:

- Points to cheekycj

Please leave any comments here within the next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

girionis
EE Cleanup Volunteer