日期:2014-05-17 浏览次数:23464 次
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String aFilePath = null; //要下载的文件路径 String aFileName = null; //要下载的文件名 response.setHeader("pragma","no-cache"); response.setHeader("cache-control","no-cache"); response.setDateHeader("Expires",0); request.setCharacterEncoding("GBK"); try { String str = getServletContext().getRealPath("/"); str = str.replaceAll("\\\\", "/");// 转换\为/; String temp_name = request.getParameter("name");//取文件实际路径和名称 String title = request.getParameter("jc");//取下载文件的名称 String temp_1 = temp_name.substring(temp_name.lastIndexOf("."));//取扩展名 aFilePath = str; aFileName = temp_name.substring(temp_name.lastIndexOf("/")+1); //碰到title中有.的,取最后一个.的前面部分作为title if(title.lastIndexOf(".")!= -1)title = title.substring(0,title.lastIndexOf(".")); String abc = title+temp_1; String newsName = java.net.URLDecoder.decode(abc,"GBK"); response.setContentType("text/x-msdownload"); //response.addHeader("Content-Disposition","attachment; filename=\"" + new String(abc.getBytes("GBK"),"utf-8") + "\""); response.addHeader("Content-Disposition","attachment; filename=\"" + new String(newsName.getBytes(),"ISO-8859-1") + "\""); java.io.OutputStream os = null; java.io.FileInputStream fis = null; try { os = response.getOutputStream(); fis = new java.io.FileInputStream(aFilePath + temp_name); byte[] b = new byte[1024]; int j = 0; while ((j = fis.read(b)) > 0) { os.write(b, 0, j); } fis.close(); os.flush();//报错信息指向了这行 os.close(); } catch (Exception e) { e.printStackTrace(); } /// } catch(Throwable e) { //log.error("FileDownload doGet() IO error!",e); } }