我有一个服务,它将一些属性添加到文件中并在响应中作为字节数组发送回来,但我很难显示它,因为它是字节,我试图将它转换为base64,但它仍然没有'工作。它显示原始字节
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 :(得分: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`;
};
答案 1 :(得分:0)
好吧,我的搜索将我引到了这里。这是我解决“响应中发送的字节数组显示图像”问题的方法。来自show-byte-array-content-as-image的@amdev的评论特别有用。这里是关键点:
data
URL显示它。Java Spring后端
@RequestMapping(value = "/**")
public @ResponseBody JsonResponse getImage(...) throws URISyntaxException {
...
// the meat
RestTemplate restTemplate = new RestTemplate();
JsonResponse response = new JsonResponse(); // our own JSON marshaller class
try {
// pull image from a web api returning a byte array but this could be a call
// to a database returning a byte array
ResponseEntity<byte[]> imageBytes = restTemplate.exchange(url, method, httpEntity, byte[].class);
byte[] imageBytesBody = imageBytes.getBody();
String b64 = Base64.encodeBase64String(imageBytesBody);
response.setSuccess(b64);
// JSON message is {status: 'success', result: 'b64 - the image in base 64 format'}
}
catch(RestClientException x) {
response.setError(x);
// JSON message is {status: 'error', result: 'error blah blah blah'}
}
return response;
}
JavaScript jQuery前端
$.ajax({
type: 'GET',
url: '/image',
...
})
.done(function(response) {
$('body').append('<img src="data:image/png;base64,' + response.result + '" />');
});
希望这会有所帮助。