java文件下载和在线打开
/** * @author chenzheng * @since 2013-9-10 * @Description: java下载 * @throws * @param filePath * @param response * @param isOnLine * @throws Exception * void */public void downLoad() throws Exception {String paths=ServletActionContext.getServletContext().getRealPath("/");System.out.println(paths);String filePath="F:\\哈哈.txt";boolean isOnLine=false;HttpServletResponse response = ServletActionContext.getResponse();response.setCharacterEncoding("utf-8"); File f = new File(filePath); if (!f.exists()) { response.sendError(404, "File not found!"); return; } BufferedInputStream br = new BufferedInputStream(new FileInputStream(f)); byte[] buf = new byte[1024]; int len = 0; response.reset(); // 非常重要 String filename=new String(f.getName().getBytes("gbk"),"iso-8859-1"); if (isOnLine) { // 在线打开方式 URL u = new URL("file:///" + filePath); response.setContentType(u.openConnection().getContentType()); response.setHeader("Content-Disposition", "inline; filename=" + f.getName()); // 文件名应该编码成UTF-8 } else { // 纯下载方式 response.setContentType("application/x-msdownload"); response.setHeader("Content-Disposition", "attachment; filename=" +filename ); } OutputStream out = response.getOutputStream(); while ((len = br.read(buf)) > 0) out.write(buf, 0, len); br.close(); out.close(); }
?