Unicode编码:保存二进制图片

本文介绍了一种通过Base64编码处理Cookie中的二进制数据的方法,具体展示了如何将图片文件编码为Base64字符串存储在Cookie中,并在客户端解析还原该图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;

        }

    }

   

%>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值