base64.jsp--页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="java.io.File"%><%@page import="java.io.InputStream"%>
<%@page import="sun.misc.BASE64Encoder"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>cookie encoding</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<%
System.out.println("根目录下的图片路径="+this.getServletContext().getRealPath("cookie.gif"));
File file=new File(this.getServletContext().getRealPath("cookie.gif"));
byte[] binary=new byte[(int)file.length()];
InputStream ins=this.getServletContext().getResourceAsStream(file.getName());
ins.read(binary);
ins.close();
String content=BASE64Encoder.class.newInstance().encode(binary);
Cookie cookie=new Cookie("file",content);
response.addCookie(cookie);
%>
</head>
<body>
从Cookie 中获取的二进制图片:<img alt="" src="base64_decode.jsp"><br/>
<textarea id='cookieArea' style='width: 100%;heigh:800px;'></textarea>
<script type="text/javascript">cookieArea.value=document.cookie;</script>
</body>
</html>
base64_decode.jsp--页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="sun.misc.BASE64Decoder"%>
<%
out.clear();
for(Cookie cookie:request.getCookies()){
if(cookie.getName().equals("file")){
byte[] binary=BASE64Decoder.class.newInstance().decodeBuffer(cookie.getValue().replace(" ",""));
response.setHeader("Content-Type","image/gif");
response.setHeader("Content-Disposition","inline;filename=cookie.gif");
response.setHeader("Connection","close");
response.setContentLength(binary.length);
response.getOutputStream().write(binary);
response.getOutputStream().flush();
response.getOutputStream().close();
}
}
out.clear();
out = pageContext.pushBody();
%>