?
Solved

how to specify relative path in jsp

Posted on 2003-02-21
22
Medium Priority
?
769 Views
Last Modified: 2007-12-19
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

0
Comment
Question by:vamshicheruku
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 7
  • 2
  • +2
22 Comments
 

Expert Comment

by:pat5
ID: 7995685
i think your path should have this in <a>
<a href="../WEB-INF/classes/registration/files/somefilename.ext"></a>
hope this will help u.
0
 
LVL 19

Accepted Solution

by:
cheekycj earned 140 total points
ID: 7996674
use ServletContext.getRealPath()

String path = request.getRealPath(request.getServletPath());
// may not need the "/"
java.io.FileInputStream fileInputStream =new java.io.FileInputStream(path + "/" + filename);

CJ
0
 
LVL 14

Expert Comment

by:kennethxu
ID: 7996789
anything under web-inf is not directly accessable by client. put your files in other dir, e.g. WebRegistration/file
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:vamshicheruku
ID: 7996940
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
0
 
LVL 14

Expert Comment

by:kennethxu
ID: 7997112
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();
0
 
LVL 14

Expert Comment

by:kennethxu
ID: 7997304
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
0
 

Author Comment

by:vamshicheruku
ID: 7997578
this is not working kennethxu
0
 

Expert Comment

by:pat5
ID: 7997641
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.



0
 
LVL 14

Expert Comment

by:kennethxu
ID: 7999252
>> this is not working kennethxu
what error message did you get?
0
 
LVL 14

Expert Comment

by:kennethxu
ID: 8000422
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
0
 

Author Comment

by:vamshicheruku
ID: 8031158
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
0
 
LVL 19

Expert Comment

by:cheekycj
ID: 8035201
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.
0
 
LVL 14

Expert Comment

by:kennethxu
ID: 8035377
>> 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.
0
 
LVL 14

Expert Comment

by:kennethxu
ID: 8035698
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 );
     }
}
0
 

Author Comment

by:vamshicheruku
ID: 8036184
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


0
 

Author Comment

by:vamshicheruku
ID: 8036286
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


0
 
LVL 14

Expert Comment

by:kennethxu
ID: 8036475
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
0
 

Author Comment

by:vamshicheruku
ID: 8036647
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


0
 

Author Comment

by:vamshicheruku
ID: 8060273
hi kenneth,

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

regards,
vamshi
0
 
LVL 14

Expert Comment

by:kennethxu
ID: 8060322
let me know if you need help trying it out :)
0
 
LVL 35

Expert Comment

by:girionis
ID: 9990259
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
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In the absence of a fully-fledged GPO Management product like AGPM, the script in this article will provide you with a simple way to watch the domain (or a select OU) for GPOs changes and automatically take backups when policies are added, removed o…
Introducing Priority Question, our latest feature.
Michael from AdRem Software outlines event notifications and Automatic Corrective Actions in network monitoring. Automatic Corrective Actions are scripts, which can automatically run upon discovery of a certain undesirable condition in your network.…
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question