Download Files using JSP Page....

Hi Guys,

My application allows users to upload files to the server.so when i'm uploading them...i'm even storing the path of that in the database. Now i've a form where i'm bringing up these paths a downloadable links.

My problem is ....the path is proper and even the files are present on the server but when i click on the link i'm not getting the download pop up which should have Open - save - cancel.

Instead its taking to that page link and a blank screen is displayed on the browser with the link path i clicked as the address in the addressbar...

and even i tried saving it by clicking on the save target as - now the file is getting stored as extended html format.

and more over when i get a blank screen....even though i clicked the back button its not taking me to the previous page...



thankz
LVL 10
jagadeesh_motamarriAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

fargoCommented:
Hi,

u can make use of code as below.. if the file resides on the server side, u need to know the content type to pop up the correct rendering... here the code reads the content as stream and outputs it. Hope it helps.

            String fileName = request.getParameter("filename");
            String contentType = request.getParameter("contentType");

            if(!StringUtils.isEmpty(contentType)){
                  response.setContentType(contentType);
                  response.setHeader("Content-Disposition","inline");
                  
            }else{
                  // default content type
                  response.setContentType("application/octet-stream");
                  response.setHeader(
                        "Content-Disposition",
                        "attachment; filename=\""+fileName+"\";");
            }
            

            String filePath = // define the path with file name
            logger.debug("File Path is :" + filePath);

            boolean exists = (new File(filePath)).exists();
            if (exists)
            {
                  try
                  {
                        this.downloadFile(filePath, response);
                  }
                  catch (IOException e)
                  {
                        logger.error("", e);
                  }
            }

      }

      public void downloadFile(String filepath, HttpServletResponse response)
            throws IOException
      {

            File F = new File(filepath);
            ServletOutputStream out = response.getOutputStream();
            InputStream in = null;
            try
            {
                  in = new BufferedInputStream(new FileInputStream(F));
                  int ch;
                  while ((ch = in.read()) != -1)
                  {
                        out.print((char) ch);
                  }
            }
            catch (Exception ex)
            {
                  logger.error("", ex);
            }

            finally
            {
                  if (in != null)
                        in.close();
                  out.close();
            }

      }

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
jagadeesh_motamarriAuthor Commented:
Hi Fargo....

So this should happen when i click on the link...
0
KuldeepchaturvediCommented:
what kind of files are these? I mean what are the extensions?
Fargo's code will work for everything but normally you dont have to do this much of coding to get a file downloaded by the browser..
0
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

jagadeesh_motamarriAuthor Commented:
any type....rather should say ...all types
0
KuldeepchaturvediCommented:
where you are saving your files on the server? I mean are they accessible via web? ( are they inside the virtual directory or outside)..
if you type the url to your file on the browser how the browser reacts?
0
jagadeesh_motamarriAuthor Commented:
Hi Fargo....u mean i need to create another servlet for this action to happen....

I prefer doing this in the jsp page itself..
0
jagadeesh_motamarriAuthor Commented:
when i type upto the parent directory ...i'm able to see the files and their details....


when i click on the link i'm not getting the download pop up which should have Open - save - cancel.

Instead its taking to that page link and a blank screen is displayed on the browser with the link path i clicked as the address in the addressbar...
0
KuldeepchaturvediCommented:
you sure that your files got uploaded correctly!!!.... if you have access to the server, can you open these files normally??

( i.e.  a .doc file in word, a .pdf in acrobat etc)..??
0
jagadeesh_motamarriAuthor Commented:
yea the files are uploaded correctly ....i can even see the files names and theires when go the parent directory as i said earlier....
0
fargoCommented:
well...i was away for some time..the code i gave can be used in a servlet or in a jsp itself. Kuldeep, the code i gave is not that complex -:)

0
KuldeepchaturvediCommented:
>>....i can even see the files names and  my question is can you open them on server ?

Fargo, I never said that your code was complex... I said that it should be doable without the coding..:-)
0
jagadeesh_motamarriAuthor Commented:
Fargo,

I've  a problem here....actually the html tags needed fo it to get as a link is prepared in the servlet itself......so when it gets back to a servlet its just a stringbuffer object...now how do i get the filename separately...

here is wat i'm doing....

      public List getChiefDetailsForClosing(int sid) {
                
                
                List searchMap1 = new ArrayList();
                Vector searchData = new Vector();
                
                mysql_c4isr conn = new mysql_c4isr();
                ResultSet rs;
                
                try {
                      String sql = "Select response_email,opinion, comment,  Date_format(submitted_on,'%M-%e-%Y')as sdate, filenames_path from response  where sid = "+sid;
                      
                      System.out.println("SQL Query: " + sql);
                      
                      rs = conn.executeQuery(sql);
                      while (rs.next()) {
                            
                            searchData.add(rs.getString("response_email"));
                            
                            if("1".equals(rs.getString("opinion")))
                                  searchData.add("Yes");
                            else if ("0".equals(rs.getString("opinion")))
                                  searchData.add("No");
                                  
                                                        
                            searchData.add(rs.getString("comment"));
                            
                            String filenames = rs.getString("filenames_path");
                            StringBuffer hold_path = new StringBuffer();
                            int i = 1;
                            StringTokenizer str = new StringTokenizer(filenames,",");
                            while(str.hasMoreTokens()){
                                  
                                  hold_path.append("<a href="+str.nextToken().toString().replaceAll("E:/Program Files/Apache Software Foundation/Tomcat 5.0/webapps/TrackingSystem/","")+">"+"file"+i+"</a>,<br/>");
                                  i++;
                            }
                            
                            System.out.println("hold_paths: "+hold_path.toString());
                            searchData.add(hold_path.toString());
                            
                            if((!"".equals(rs.getString("filenames_path").trim())) && (!"".equals(rs.getString("comment").trim())))
                                  searchData.add("Yes");
                            else
                                  searchData.add("Negative");
                            
                            searchData.add(rs.getString("sdate"));
                            
                            
                            searchMap1.add(searchData);
                            
                            
                            
                      }
                      
                } catch (SQLException se) {
                      System.out.println("SQLException status : " + se.getMessage());
                      se.printStackTrace();
                      
                } catch (Exception e) {
                      System.out.println("Some Exception " + e.getMessage());
                      e.printStackTrace();
                      
                }
                return searchMap1;
                
          }
          
...........................and then in the jsp page i just iterate the obtained searchmap1 and get it in a column and file1, file2......depending on the number of files.      
      
      
0
fargoCommented:
>>>so when it gets back to a servlet its just a stringbuffer object...now how do i get the filename separately...
I don't understand it here...could u please explain me more.

Moreover, as i see with your code..why u are hardcoding a path. You can have a path outside of tomcat and keep that as a constant variable. Display only the filename and handle the downloading/uploading related to that constant filepath.

0
jagadeesh_motamarriAuthor Commented:
instead of displaying the filename i'm displaying it as file1, file2, file3,....etc. Even if i take the file name i got to frame the links later in my jsp code since the number of files are variable for each user...


I'm sorry i said Stringbuffer instead of List...

can u just provide me a sample code of it has to be in the servlet and jsp..


thankz
0
fargoCommented:
if i understand it correcly, you are getting the complete path with file name from the resultset. Then u replace the root with "". We can add the following lines...

String fileName = str.nextToken().toString().replaceAll("E:/Program Files/Apache Software Foundation/Tomcat 5.0/webapps/TrackingSystem/","");
String servletLink = "fileDownloadServlet?fileName="+fileName;

hold_path.append("<a href=").append(servletLink).append(">"+"file"+i+"</a>,<br/>");

and the code i gave u in my first post can be a part of the servlet named "fileDownloadServlet". Let me know if i understood it correctly.
0
fargoCommented:
if u keep the above code segment inside the loop, then please init the servletLink string with null value each time.
String servletLink = null; // or empty string
servletLink = "fileDownloadServlet?fileName="+fileName;
0
jagadeesh_motamarriAuthor Commented:
Getting an error here....
 boolean exists = (new File(filePath)).exists();
          if (exists)
          {


lemma try....
0
jagadeesh_motamarriAuthor Commented:
>>  String filePath = // define the path with file name

and even this path is not fixed...it keeps changing for every user and for every task....
0
fargoCommented:
i think in your case the filepath should be

>>String filePath = // define the path with file name
String filePath = "E:/Program Files/Apache Software Foundation/Tomcat 5.0/webapps/TrackingSystem/"+fileName;


0
fargoCommented:
why don't u keep the file path constant? what's the need of making it change for each user and task?

if that's the case, u have to append the filePath as a parameter, as we did for fileName in the link for the servlet.
0
jagadeesh_motamarriAuthor Commented:
says...>>    if(!StringUtils.isEmpty(contentType)){
can not be resolved...


and if i import com.mysql.jdbc.StringUtils;...there is no isEmpty method defined...
0
fargoCommented:
ok. the StringUtils is a class from jakarta commons lang package. U can replace that with
 if(contentType!=null && !contentType.equals("")){

in your case, i think u don't know about the content type of the files..correct? in that case, avoid checking it and keep it always as octet-stream.(the second block in my posted code)


0
jagadeesh_motamarriAuthor Commented:
a grt8 start ....

So this is what i have now in the servlet....

      String fileName = request.getParameter("filename");
        String contentType = request.getParameter("contentType");

        if(contentType!=null && !contentType.equals("")){

             response.setContentType(contentType);
             response.setHeader("Content-Disposition","inline");
             
        }else{
             // default content type
             response.setContentType("application/octet-stream");
             response.setHeader(
                  "Content-Disposition",
                  "attachment; filename=\""+fileName+"\";");
        }
       

        String filePath = "E:/Program Files/Apache Software Foundation/Tomcat 5.0/webapps/TrackingSystem/"+fileName;

        boolean exists = (new File(filePath)).exists();
        if (exists)
        {
             try
             {
                  this.downloadFile(filePath, response);
             }
             catch (IOException e)
             {
                e.printStackTrace();
             }
        }



and then the method downloadFile..

..........................
In the JSP page i'm able to get the links and when i press on them i could see the window with Save - open - cancel options.

But unfortunately....it has File Name : null and type: unknow file type.
0
fargoCommented:
hi please check whether the filename parameter from the link is same as u r handling in servlet

String fileName = request.getParameter("filename");
OR
String fileName = request.getParameter("fileName");

depending upon the parameter we appended in the servlet link.

P.S: I am off now and will be back in some hours. You are just at the end of this...good luck

0
fargoCommented:
Jagdeesh..is ur problem solved?
0
jagadeesh_motamarriAuthor Commented:
Thank God...i was literally waiting to hear from u...

I did not solve...


i changed the filename according but still no luck
0
fargoCommented:
can u show the html link generated for download?
0
jagadeesh_motamarriAuthor Commented:
i'm able to see the dialog box with the size of the file correctly but the name and type in the dialog box are not coming up properly
0
jagadeesh_motamarriAuthor Commented:
Yea..it here

<a href=FileDownload?filename=Suspense_Uploads/4_1/java_faq.rtf> file1</a>

0
fargoCommented:
what r u getting with the following in the servlet??
String fileName = request.getParameter("filename");

0
jagadeesh_motamarriAuthor Commented:
I'm getting -

filename= Suspense_Uploads/4_1/java_faq.rtf
0
fargoCommented:
is there any error u r getting in servlet?
0
jagadeesh_motamarriAuthor Commented:
no errors...
0
fargoCommented:
is this true ? boolean exists = (new File(filePath)).exists();
0
jagadeesh_motamarriAuthor Commented:
yes....
0
fargoCommented:
and u r getting
it has File Name : null and type: unknow file type.

can u please remove this code
if(contentType!=null && !contentType.equals("")){

             response.setContentType(contentType);
             response.setHeader("Content-Disposition","inline");
             
        }
0
jagadeesh_motamarriAuthor Commented:
Here is my complete observation so far....

When i click on a file to download which is other than text file....its like this in the download dialog box

Name: FileDownload (which is servlet name)
Type: unknown File Type
From: garuda (my system name)

When i click on a file that is text file ..its like this-


Name: FileDownload (which is servlet name) (still the name thing)
Type: HTML Document, 115 bytes
From: garuda (my system name)

here when i click save thought he type it is showing in the dialog box as HTML document, 115 bytes -when it goes to the browse are...i mean where i select the path to store it is saving it with the servlet name by default as the text file and then i could see the contents also.....


0
jagadeesh_motamarriAuthor Commented:
One more thing......even if its not a text file if i save it and change the corresponding extension with what it is - i'm able to see the contents also...let it be ppt or pdf pr what ever...

now the problem is with the

Name :
Type:

they are not proper
0
fargoCommented:
that's almost a correct behaviour. B'coz when the browser doesn't understand the file type it say unknown..and if the file type is txt..it considers the default rendering of html/text and so does the message.

That is why in my servlet i have handling with content-type, so that we can set correct content type to the response and then a correct download box and application will be selected.

But in your case there is no way u are storing the content type. One ugly way is to parse the filename and get the extension of the file and set the content type accordingly.

What is happening when the unknown file type is saved and opened later..is it saved and open correctly? Overall download is working..correct?
0
jagadeesh_motamarriAuthor Commented:
yea overall downloading is correct.

when i save he unknown file ype: it is just saving it by default with the servlet name and type as document ....n now when i change the extension..it works
0
fargoCommented:
Jagdessh..untill unless u see some way to get the correct content type..this behaviour is normal.

U can carry on with the ugly way i said in my last post...get the extension..and set the content type accordingly.
0
jagadeesh_motamarriAuthor Commented:
But how abut the file name...its always the servlet name...
0
fargoCommented:
actually it should not be servlet name. Just one q. why r u setting the file name with directory names like Suspense_Uploads/4_1/java_faq.rtf why not only java_faq.rtf

try it without directory names..should work
0
jagadeesh_motamarriAuthor Commented:
becoz all the files are not stored in a same directory......4_1 keeps changing everytime...
0
fargoCommented:
for testing..just try it with filename only..like  java_faq.rtf to see if it works.
0
jagadeesh_motamarriAuthor Commented:
yea i did....its has not effect...
0
jagadeesh_motamarriAuthor Commented:
hey..sorry it worked if its just the filename within...
0
jagadeesh_motamarriAuthor Commented:
please sugget me somthing in this regard...
0
jagadeesh_motamarriAuthor Commented:
something like regular expression that would replace

Suspense_Uploads/[anything]/       to just "";

thankz
0
fargoCommented:
yes..u have to get the real file name out of the filename u r setting for servlet handling.

file path for servlet: Suspense_Uploads/[anything]/filename.pdf
u need to have : filename.pdf >> this particular should be set in the below code

response.setContentType("application/octet-stream");
             response.setHeader(
                  "Content-Disposition",
                  "attachment; filename=\""+fileName+"\";");


u need to parse the filename out of the path.
0
jagadeesh_motamarriAuthor Commented:
well..here is what i did..

 StringTokenizer s = new StringTokenizer(fileName,"/");
        String n = "";
        while(s.hasMoreTokens()){
              n = s.nextToken().toString();
              
              
        }

now n has filename by itself....its working grt8.


Thankz a lot for all your effoerts...
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JSP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.