javascript 在角度js中将字节数组显示为图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31198509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
display byte array as image in angular js
提问by axn7975
I have an image in database. I want to retreive the image and display it in web page using angular js. After fetching data i have byte array. How do i send the data to the html page. I am having issues with the below code.. Kindly help.
When i click the link to view the image, page is sending 2 get requests to the server instead of one. It is sending request continuously for 2 times.
我在数据库中有一个图像。我想检索图像并使用 angular js 在网页中显示它。获取数据后,我有字节数组。我如何将数据发送到 html 页面。我在使用以下代码时遇到问题.. 请帮忙。
当我单击链接查看图像时,页面向服务器发送了 2 个获取请求,而不是一个。它连续发送请求 2 次。
Note : I have tried using the below link.. But it didn't work
注意:我试过使用下面的链接..但它没有用
AngularJS - Show byte array content as image
Below is my js file
下面是我的js文件
app.controller('aboutCtrl', function($scope,$http,$location) {
$scope.message = 'This is Add new order screen';
var url = '/Angular/login';
$http.get(url).success(function(result) {
$scope.image = result.image;
})
});
//html
<img data-ng-src="data:image/PNG;base64,{{image}}">
Java class file
Java类文件
public String getImage() throws FileNotFoundException{
String byteStr=null;
try
{
Connection con= DbConnect.getConnection();
String sql ="select * from image_data where id=1";
PreparedStatement ps=con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
Blob b=rs.getBlob(2);
byte barr[]=b.getBytes(1,(int)b.length());
byteStr = new String(barr);
}
}catch(Exception e){
e.printStackTrace();
}
return byteStr;
}
Servlet Code
服务程序代码
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("inside get");
JSONObject result= new JSONObject();
Retreive rt = new Retreive();
result.put("image", rt.getImage());
response.setContentType("application/json");
PrintWriter out = response.getWriter();
out.write(result.toString());
out.flush();
out.close();
}
回答by David Votrubec
Seems like your image
is not base64 encoded string but still that byte array. You need to encoded it first in order to use it like this <img data-ng-src="data:image/PNG;base64,{{image}}">
似乎您image
的不是 base64 编码的字符串,但仍然是该字节数组。您需要先对其进行编码才能像这样使用它<img data-ng-src="data:image/PNG;base64,{{image}}">
Check the documentation AngularJS - Show byte array content as image
You can also try this approach https://gist.github.com/jonleighton/958841