2017-05-01 55 views
0

我有一个服务,它添加了一些属性文件,并将其作为字节数组返回给响应,但我很难显示它,因为它是字节,我试图将其转换到base64,但它仍然没有奏效。它显示了原始字节AngularJS显示图像从字节数组发送作为回应

PNG

IHDR & LCvIDATx ......

什么是解决这个也许我应该改变的反应最好的解决办法类型是否可以发送不是字节?

@RequestMapping(path = "image/decode", method = POST, consumes = "multipart/form-data", produces = {"image/png", "image/jpeg"}) 
public byte[] decodeImage(@RequestParam("file") MultipartFile file) throws Exception { 
    File file1 = addProperties(file); 
    return FileUtils.readFileToByteArray(file1); 
} 

JS代码

$scope.extractImage = function (sourceFile) { 
    Upload.upload({ 
     url: '/image/decode', 
     objectKey: '', 
     data: { 
      file: sourceFile 
     } 
    }).then(function (response) { 
     console.log('Success ' +'Response: ' + response); 
     $scope.image = response.data; 
    }, function (response) { 
     console.log('Error status: ' + response); 
    }); 
}; 

HTML代码

<img class="thumb image-properties" ng-if="image" ng-src="{{image}}" /> 
+0

尝试将其转换为数据URI: 'data:image/png; base64,<转换为Base64的数据>' – Riiverside

+1

[Javascript:如何使用Javascript或Servlet显示字节数组中的图像?](http://stackoverflow.com/questions/20756042/javascript - 如何对显示器 - image-from-byte-array-using-javascript-or-servlet) –

+0

其实更好的重复会是:http://stackoverflow.com/questions/14979791/angularjs-show-byte-array-content-as-image –

回答

0

想必你已经找到了解决方案。如果不是

var bytes = response.data; 
    var base64String = btoa(String.fromCharCode.apply(null, new Uint8Array(bytes))); 
    $scope.image = "data:image/png;base64," + base64String; 

其他人同样的问题,这个问题有一个更容易的解决方案:

@GetMapping(path = "image/decode/{img}", produces = {"image/png", "image/jpeg"}) 
public byte[] decodeImage(@PathVariable String img) throws Exception { 
    // return your file's bytes 
} 

和JS:

$scope.extractImage = function (sourceFile) { 
    $scope.image = `/image/decode/$sourceFile`; 
}; 
相关问题