Unicode編碼:保存二進制圖片

Cookie不僅可以使用ASCII字符與Unicode字符,還可以使用二進制數據。

例如數字證書,提高安全度。使用二進制數據時也需要進行編碼

保存二進制數據內容,不實用。Cookie內容過多,影響速度。應少而精

base64.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" isErrorPage="true"%>

<jsp:directive.page import="java.io.File"/>

<jsp:directive.page import="java.io.InputStream"/>

<jsp:directive.page import="sun.misc.BASE64Encoder"/>

<%

    File file = new File(this.getServletContext()

.getRealPath("cookie.gif"));

    byte[] binary = newbyte[(int)file.length()];

    //從圖片文件讀取二進制數據

    InputStream is = this.getServletContext()

.getResourceAsStream(file.getName());

    is.read(binary);

    is.close();

   

    String content = BASE64Encoder.class.newInstance().encode(binary);

    Cookie cookie = new Cookie("file",content);

    response.addCookie(cookie); //將二進制數據發送客戶端

   

%>

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

   

    <title>My JSP 'index.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">

    <meta http-equiv="cache-control" content="no-cache">

    <meta http-equiv="expires" content="0">   

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

    <meta http-equiv="description" content="This is my page">

    <!--

    <link rel="stylesheet" type="text/css" href="styles.css">

    -->

  </head>

 

  <body>

    Cookie中獲取到的二進制圖片:<img src="base64_decode.jsp"/><br/>

    <textarea id="cookieArea" style="width:500;height:200px;">

</textarea>

    <script type="text/javascript">

        cookieArea.value = document.cookie;

    </script>

  </body>

</html>

 

base64_decode.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" isErrorPage="true"%>

<jsp:directive.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();

            return;

        }

    }

   

%>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章