AngularJS+Spring Boot如何从后台读取并显示图片

AngularJS+Spring Boot如何从后台读取并显示图片


  • 原理:
    1.前台向后台发送请求,设置头部的responseType: 'arraybuffer'来接受图片的二进制流。
    2.后台读取对应的图片,然后以二进制流的形式返回给前台。
    3.前台用Blob来重新生成图片,并用URL.createObjectURL()来生成图片的url。
  • 代码如下:
    html:
<img ng-src="{{image}}">

js:

$http({
    url:"",
    method: "get",
    params: params,
    responseType:"arraybuffer"
}).success(function(res){
    var blob = new Blob([data], {type: "image/jpeg"});
    $scope.image = URL.createObjectURL(blob );
})

后台:

@RequestMapping(value = "/image", method = GET)
@ResponseBody
public byte[] getImage(String imagePath) {
        ClassPathResource resource = new ClassPathResource(IMAGEPATH+imagePath);
        byte[] buffer = null;
        try {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            FileInputStream fis = new FileInputStream(resource.getFile());
            byte[] b = new byte[1024];
            int length;  
            while ((length = fis.read(b)) != -1)  
            {  
                output.write(b, 0, length);  
            }
            buffer = output.toByteArray();
            output.close();
            fis.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return buffer;
    }

你可能感兴趣的:(spring-boot,angularjs)