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
public String hyperlink1_action() {
this.getSessionBean1().setDownloadFile((String)hyperlink1.getText());
return "download";
}
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();
}