//於 Servlet 設定 ContentType 與 Header,讓瀏覽器知道不要以應用程式開啟
// Set the headers.
res.setContentType("application/x-download");
res.setHeader("Content-Disposition", "attachment; filename=" + filename);
// Send the file.
OutputStream out = res.getOutputStream( );
returnFile(filename, out);
//returnFile 實作內容
public static void returnFile(String filename, OutputStream out) throws FileNotFoundException, IOException { InputStream in = null; try { in = new BufferedInputStream(new FileInputStream(filename)); byte[ ] buf = new byte[4 * 1024]; // 4K buffer int bytesRead; while ((bytesRead = in.read(buf)) != -1) { out.write(buf, 0, bytesRead); } } finally { if (in != null) in.close( ); } }
參考網址:
http://onjava.com/pub/a/onjava/excerpt/jebp_3/index1.html?page=2
http://onjava.com/pub/a/onjava/excerpt/jebp_3/index3.html