base64 html 图片
·
服务器端代码
package com.easyui.controller;
import sun.misc.BASE64Encoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Base64;
/**
* Created by baich on 2016/4/10.
*/
@WebServlet(name = "MenuController", value = "MenuController")
public class MenuController extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
File file = new File("logo.png");
InputStream is = new FileInputStream(file);
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = is.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
byte[] in2b = swapStream.toByteArray();
BASE64Encoder en = new BASE64Encoder();
String result = en.encode(in2b);
System.out.println(result);
writer.write(result);
writer.flush();
writer.close();
}
}
页面代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="common/jquery-easyui-1.4.5/jquery.min.js"></script>
</head>
<body>
<img id="img" src="" alt="222222222222">
<script>
$.ajax({ // 这里使用到Jquery的ajax方法
type: "POST",
dataType: "text",
async: false,
url: "/easyui/MenuController",
success: function (data) {
var dt = data;
$("#img").attr("src", "data:image/png;base64," + data);
}
});
</script>
</body>
</html>
更多推荐
已为社区贡献2条内容
所有评论(0)