后端传输图片Base64数据到前端渲染
后端代码
public String sendImg(LoginUser loginUser) {
LoginUser loginUser1 = loginUserMapper.selectOne(new LambdaQueryWrapper<LoginUser>().eq(LoginUser::getAccount, loginUser.getAccount()));
String profile = loginUser1.getProfile();
String imgPath = "";
if (property.startsWith(OsName.WINDOWS.toString().toLowerCase())) {
imgPath = "D:\\bg\\" + profile;
} else if (property.startsWith(OsName.LINUX.toString().toLowerCase())) {
imgPath = "\\usr\\imgPath" + profile;
}
FileInputStream inputStream = null;
String base64Str = "";
try {
Base64.Encoder encoder = Base64.getEncoder();
inputStream = new FileInputStream(imgPath);
int available = inputStream.available();
byte[] bytes = new byte[available];
inputStream.read(bytes);
base64Str = encoder.encodeToString(bytes);
} catch (Exception e) {
e.printStackTrace();
}
return base64Str;
}
前端代码
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<script>
function sendImg() {
$.ajax({
type: "POST",
url: "http://127.0.0.1:8080/users/sendImg",
data: {
account:"admin",
password:"admin"
},
success: function (result) {
console.log(result)
function c(){
var cc=new Image();
cc.src="data:image/jpg;base64,"+ result;
document.getElementById("d1").appendChild(cc);
}
c();
}
})
}
</script>
<style>
img{
width: 300px;
height: 300px;
}
</style>
<body>
<div id="d1"></div>
<input type="button" value="发送" onclick="sendImg()">
</body>
效果展示
![在这里插入图片描述](https://img-blog.csdnimg.cn/53fb7fc2f6464a0fb86a4a25c4780ba9.png)