[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Download Files using JSP Page....

Posted on 2006-04-16
51
Medium Priority
?
330 Views
Last Modified: 2012-08-13
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
0
Comment
Question by:jagadeesh_motamarri
  • 27
  • 20
  • 4
51 Comments
 
LVL 11

Accepted Solution

by:
fargo earned 2000 total points
ID: 16467355
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
 
LVL 10

Author Comment

by:jagadeesh_motamarri
ID: 16467365
Hi Fargo....

So this should happen when i click on the link...
0
 
LVL 19

Expert Comment

by:Kuldeepchaturvedi
ID: 16467385
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
Independent Software Vendors: 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!

 
LVL 10

Author Comment

by:jagadeesh_motamarri
ID: 16467387
any type....rather should say ...all types
0
 
LVL 19

Expert Comment

by:Kuldeepchaturvedi
ID: 16467392
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
 
LVL 10

Author Comment

by:jagadeesh_motamarri
ID: 16467393
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
 
LVL 10

Author Comment

by:jagadeesh_motamarri
ID: 16467401
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
 
LVL 19

Expert Comment

by:Kuldeepchaturvedi
ID: 16467411
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
 
LVL 10

Author Comment

by:jagadeesh_motamarri
ID: 16467423
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
 
LVL 11

Expert Comment

by:fargo
ID: 16467490
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
 
LVL 19

Expert Comment

by:Kuldeepchaturvedi
ID: 16467559
>>....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
 
LVL 10

Author Comment

by:jagadeesh_motamarri
ID: 16468890
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
 
LVL 11

Expert Comment

by:fargo
ID: 16468944
>>>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
 
LVL 10

Author Comment

by:jagadeesh_motamarri
ID: 16468997
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
 
LVL 11

Expert Comment

by:fargo
ID: 16469149
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
 
LVL 11

Expert Comment

by:fargo
ID: 16469162
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
 
LVL 10

Author Comment

by:jagadeesh_motamarri
ID: 16469225
Getting an error here....
 boolean exists = (new File(filePath)).exists();
          if (exists)
          {


lemma try....
0
 
LVL 10

Author Comment

by:jagadeesh_motamarri
ID: 16469237
>>  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
 
LVL 11

Expert Comment

by:fargo
ID: 16469244
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
 
LVL 11

Expert Comment

by:fargo
ID: 16469261
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
 
LVL 10

Author Comment

by:jagadeesh_motamarri
ID: 16469283
says...>>    if(!StringUtils.isEmpty(contentType)){
can not be resolved...


and if i import com.mysql.jdbc.StringUtils;...there is no isEmpty method defined...
0
 
LVL 11

Expert Comment

by:fargo
ID: 16469298
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
 
LVL 10

Author Comment

by:jagadeesh_motamarri
ID: 16469359
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
 
LVL 11

Expert Comment

by:fargo
ID: 16469386
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
 
LVL 11

Expert Comment

by:fargo
ID: 16471409
Jagdeesh..is ur problem solved?
0
 
LVL 10

Author Comment

by:jagadeesh_motamarri
ID: 16471455
Thank God...i was literally waiting to hear from u...

I did not solve...


i changed the filename according but still no luck
0
 
LVL 11

Expert Comment

by:fargo
ID: 16471477
can u show the html link generated for download?
0
 
LVL 10

Author Comment

by:jagadeesh_motamarri
ID: 16471480
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
 
LVL 10

Author Comment

by:jagadeesh_motamarri
ID: 16471489
Yea..it here

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

0
 
LVL 11

Expert Comment

by:fargo
ID: 16471560
what r u getting with the following in the servlet??
String fileName = request.getParameter("filename");

0
 
LVL 10

Author Comment

by:jagadeesh_motamarri
ID: 16471587
I'm getting -

filename= Suspense_Uploads/4_1/java_faq.rtf
0
 
LVL 11

Expert Comment

by:fargo
ID: 16471633
is there any error u r getting in servlet?
0
 
LVL 10

Author Comment

by:jagadeesh_motamarri
ID: 16471640
no errors...
0
 
LVL 11

Expert Comment

by:fargo
ID: 16471657
is this true ? boolean exists = (new File(filePath)).exists();
0
 
LVL 10

Author Comment

by:jagadeesh_motamarri
ID: 16471663
yes....
0
 
LVL 11

Expert Comment

by:fargo
ID: 16471690
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
 
LVL 10

Author Comment

by:jagadeesh_motamarri
ID: 16471763
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
 
LVL 10

Author Comment

by:jagadeesh_motamarri
ID: 16471811
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
 
LVL 11

Expert Comment

by:fargo
ID: 16471828
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
 
LVL 10

Author Comment

by:jagadeesh_motamarri
ID: 16471849
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
 
LVL 11

Expert Comment

by:fargo
ID: 16471866
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
 
LVL 10

Author Comment

by:jagadeesh_motamarri
ID: 16471876
But how abut the file name...its always the servlet name...
0
 
LVL 11

Expert Comment

by:fargo
ID: 16471905
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
 
LVL 10

Author Comment

by:jagadeesh_motamarri
ID: 16471919
becoz all the files are not stored in a same directory......4_1 keeps changing everytime...
0
 
LVL 11

Expert Comment

by:fargo
ID: 16471955
for testing..just try it with filename only..like  java_faq.rtf to see if it works.
0
 
LVL 10

Author Comment

by:jagadeesh_motamarri
ID: 16471965
yea i did....its has not effect...
0
 
LVL 10

Author Comment

by:jagadeesh_motamarri
ID: 16471977
hey..sorry it worked if its just the filename within...
0
 
LVL 10

Author Comment

by:jagadeesh_motamarri
ID: 16471981
please sugget me somthing in this regard...
0
 
LVL 10

Author Comment

by:jagadeesh_motamarri
ID: 16472005
something like regular expression that would replace

Suspense_Uploads/[anything]/       to just "";

thankz
0
 
LVL 11

Expert Comment

by:fargo
ID: 16472031
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
 
LVL 10

Author Comment

by:jagadeesh_motamarri
ID: 16472249
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

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Microsoft Office Picture Manager was included in Office 2003, 2007, and 2010, but not in Office 2013. Users had hopes that it would be in Office 2016/Office 365, but it is not. Fortunately, the same zero-cost technique that works to install it with …
LinkedIn blogging is great for networking, building up an audience, and expanding your influence as well. However, if you want to achieve these results, you need to work really hard to make your post worth liking and sharing. Here are 4 tips that ca…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
With just a little bit of  SQL and VBA, many doors open to cool things like synchronize a list box to display data relevant to other information on a form.  If you have never written code or looked at an SQL statement before, no problem! ...  give i…
Suggested Courses
Course of the Month19 days, 11 hours left to enroll

872 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