后端传输图片Base64数据到前端渲染
生活随笔
收集整理的這篇文章主要介紹了
后端传输图片Base64数据到前端渲染
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
后端傳輸圖片Base64數(shù)據(jù)到前端渲染
后端代碼
public String sendImg(LoginUser loginUser) {//在數(shù)據(jù)庫中查找對應用戶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 {//new 一個base64編碼器Base64.Encoder encoder = Base64.getEncoder();//通過圖片路徑獲取輸入流inputStream = new FileInputStream(imgPath);//通過輸入流長度創(chuàng)建對應長度的byte數(shù)組int available = inputStream.available();byte[] bytes = new byte[available];//從(來源)輸入流中(讀取內(nèi)容)讀取的一定數(shù)量字節(jié)數(shù),并將它們存儲到(去處)緩沖區(qū)數(shù)組b中inputStream.read(bytes);//對byte數(shù)組進行轉(zhuǎn)碼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",// async: false, // 重點,false是同步,true是異步// dataType:'json', // 需要寫上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="發(fā)送" onclick="sendImg()"> </body>效果展示
總結(jié)
以上是生活随笔為你收集整理的后端传输图片Base64数据到前端渲染的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: “联通云”正式浮出水面 要讲出云计算怎样
- 下一篇: 史上最最最没用程序——自写平衡化学方程式