我使用
MediaType.IMAGE_JPEG
从本地文件返回图像源。如果我通过 Postman 拨打电话,我可以看到图像,但我无法成功在 HTML 上显示它。
@GetMapping(value = "/{id}/download")
public ResponseEntity<Resource> download(@PathVariable UUID id, @RequestParam String key) {
try {
final Path file = Paths.get(String.format("%s/%s", "app/resource", key));
final Resource resource = new UrlResource(file.toUri());
if (resource.exists() || resource.isReadable()) {
final HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.IMAGE_JPEG);
httpHeaders.setContentDispositionFormData("attachment", resource.getFilename());
return ResponseEntity.ok()
.headers(httpHeaders)
.body(resource);
} else {
// error
}
} catch (MalformedURLException e) {
// error
}
}
我尝试在不转换的情况下显示它,但 HTML 显示图像已损坏
<img :src=imageContent />
const { data } = await download(id, "test.jpeg");
this.imageContent = data;
我也尝试将其转换为base64,但没有成功。
<img :src=imageContent />
const { data } = await download(id, "test.jpeg");
this.imageContent =
"data:image/jpeg;base64," +
Buffer.from(data, "binary").toString("base64");
我不知道我在哪里犯了错误。我需要重构我的后端代码吗?如何显示我作为响应返回的图像?
我会将解码用作
BLOB
对象:
const { data } = await download(id, "test.jpeg");
this.imageContent =
"data:image/jpeg;base64," +
Buffer.from(data, "binary").toString("base64");
// atob() of JavaScript to decode the base chain64 in a binary chain
const decodedImageData = atob(this.imageContent);
// Create a BLOB object
const blob = new Blob([decodedImageData], { type: 'image/jpeg' });
// Create a blob object URL
const imageURL = URL.createObjectURL(blob);
this.imageURL = imageURL;
然后在图片标签上建立图片的URL:
<img src="{{ imageURL }}" alt="Image description">
尝试使用以下 MediaType:
APPLICATION_OCTET_STREAM
,例如:
// check if exists and is readable
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
此外,您可以使用ByteArrayResource:
// prepare steps
Path path = Paths.get(file.getAbsolutePath());
ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);