我正在尝试使用react-native中的<Image/>显示图像。端点使用Spring构建,并将图像内容写入输出流。端点接收映像ID。
如果我执行Postman的请求,在结果中我可以看到图像。
我在寻找解决方案,我想这是我能找到的最接近https://stackoverflow.com/a/44058739/869793的方案
我在文档中看到,它可以通过使用base64编码响应来工作,但我还没有做到这一点,我希望我可以在没有它的情况下工作。
useEffect(() => {
axios.get(
'http://localhost/images/id15',
{responseType: 'arraybuffer'}
)
.then(resp => {
const data = Buffer.from(resp.data, 'binary').toString('base64')
console.log("resp => " + data);
let imageUri = "data:image/jpeg;base64," + data;
setSource({uri: imageUri})
})
}, [])
<Image
style={styles.tinyLogo}
source={source}
/>通过混合不同的参数,我在日志中得到的输出。没有任何内容显示图像。
LOG resp => ����
LOG resp => 77+977+977+977+9
LOG resp => /f39/Q==发布于 2020-06-17 14:15:08
我最终创建了一个检索编码图像的端点。
Spring代码:
@GetMapping("/encoded-base64/{id}")
public Map<String, String> retrieveBase64EncodedImage(@PathVariable UUID id) {
return singletonMap("data", imageService.findByIdAndEncode(id));
}
public String findByIdAndEncode(UUID id) {
Image image = imageRepository.findById(id).orElseThrow();
InputStream inputStream = storageService.get(image.getFilePath());
try {
byte[] bytes = FileCopyUtils.copyToByteArray(inputStream);
return Base64.getEncoder().encodeToString(bytes);
} catch (IOException e) {
throw new RuntimeException("Cannot copy stream", e);
}
}React Native代码:
useEffect(() => {
axios.getAsync(
'path_to_server/encoded-base64/37d1302d-3ba2-4b4e-b08d-5323979abf38',
)
.then(resp => {
const data = resp.data.data
console.log("resp => " + JSON.stringify(data));
let imageUri = "data:image/jpeg;base64," + data;
setSource({uri: imageUri})
})
}, [])
<Image
style={styles.tinyLogo}
source={source}
/>https://stackoverflow.com/questions/62416362
复制相似问题