web项目以流的方式下载文件的案例

web项目以流的方式下载的案例

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String remoteAddr = request.getRemoteAddr();
		System.out.println(remoteAddr+"...");
		InputStream fis = null;
		OutputStream out = null;
		
		try {
			String path = java.net.URLDecoder.decode("D:/hehui/doc/《Effective Java中文版 第2版》.(Joshua Bloch).[PDF]&ckoo.pdf", "UTF-8");
            File file = new File(path);
            String filename = file.getName();
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();

            // 以流的形式下载文件。
            fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(filename, "UTF-8"));
            response.addHeader("Content-Length", "" + file.length());
            out = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream;chartset=utf-8");
            response.setCharacterEncoding("UTF-8");
            
            out.write(buffer);
            out.flush();
            
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(fis != null) {
				fis.close();
			}
			if(out != null) {
				out.close();
			}
		}
		
	}

 

你可能感兴趣的:(web项目以流的方式下载文件的案例)