[RSS]

How can I configure a hyperlink to download a file?

Suppose you want to create a page and place lots of links in it. What you want is, when your user clicks on a link, it should open the browser's standard Save as dialog box, even if the browser knows how to handle the MIME type. Your user can then choose a location to save the file and move on. How to do this using a hyperlink component in Netbeans Visual Web?

Here is the tip. Assume you want to let your user down a file named Sunset.jpg placed in the resources directory of the web application

  • Create a project and add a Hyperlink component to the page (Set its text property to the file name you wish to upload Ex. Sunset.jpg)
  • Add another page and name it "download"
  • Go to Navigation editor and create a link with label download from hyperlink to download page
  • In the SessionBean1 add a property by name downloadFile
  • Double click on the hyperlink and in the Java Page add the following code (Make sure the method returns "download")
     public String hyperlink1_action() {
      this.getSessionBean1().setDownloadFile((String)hyperlink1.getText());
      return "download";
     }
  • In the init() method of download page add the following code
    ServletContext context = (ServletContext) getExternalContext().getContext();
    HttpServletResponse response = (HttpServletResponse)   getExternalContext().getResponse();
    response.setContentType("application/force-download");
    String downloadFile = this.getSessionBean1().getDownloadFile();
    response.addHeader("Content-Disposition", "attachment; filename=\"" + downloadFile + "\"");
    byte[] buf = new byte[1024];
    try{
      String realPath = context.getRealPath("/resources/" + downloadFile);
      File file = new File(realPath);
      long length = file.length();
      BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
      ServletOutputStream out = response.getOutputStream();
      response.setContentLength((int)length);
      while ((in != null) && ((length = in.read(buf)) != -1)) {
         out.write(buf, 0, (int)length);
      }
      in.close();
      out.close();
    }catch (Exception exc){
      exc.printStackTrace();
    } 
  • Run the project and click on the link Sunset.jpg, browser should bring the Save As dialog.