日期:2014-05-17 浏览次数:20769 次
//下载 String filePath = filedb.getFile_url(); String filetype = filePath.substring(filePath.lastIndexOf('.')); String msg = ""; if(filePath != null && !"".equals(filePath)) { String path = getServlet().getServletContext().getRealPath("")+filePath;//找到文件 response.addHeader("Content-Disposition", "attachment; filename="+new String((filename+filetype).getBytes("gb2312"), "ISO8859-1")); response.setContentType("application/octet-stream"); ServletOutputStream output = response.getOutputStream(); InputStream fis = null; byte[] buffer = new byte[1204]; int byteRead; try { fis = new FileInputStream(path); while ((byteRead = fis.read(buffer)) != -1) { output.write(buffer, 0, byteRead); } output.flush(); } catch (Exception e) { String simplename = e.getClass().getSimpleName(); if(!"ClientAbortException".equals(simplename)) // 忽略用户点击下载取消按钮时的警告异常 { response.setContentType("text/html; charset=utf-8"); response.setHeader("Content-disposition", "inline"); output.println(" <HTML> <BODY> <P>"); output.println("文件下载发生错误!"); output.println(" </P> </BODY> </HTML>"); output.close(); } } finally { if (fis != null) { fis.close(); } } } else { msg = "找不到文件,该资料可能未上传"; } response.getWriter().write(msg); response.getWriter().flush(); response.getWriter().close(); return null;
------解决方案--------------------
String path = getServlet().getServletContext().getRealPath("")+filePath;//找到文件
response.addHeader("Content-Disposition", "attachment; filename="+new String((filename+filetype).getBytes("gb2312"), "ISO8859-1"));
response.setContentType("application/octet-stream");
还有.close写到finally里面