使用Spring,我尝试实现一个REST控制器,它可以处理请求从数据库返回BLOB对象的GET请求。
我在谷歌上搜索了一下,并将代码片段拼凑在一起,创建了以下代码片段:
@GetMapping("student/pic/studentId")
public void getProfilePicture(@PathVariable Long studentId, HttpServletResponse response) throws IOException {
Optional<ProfilePicture> profilePicture;
profilePicture = profilePictureService.getProfilePictureByStudentId(studentId);
if (profilePicture.isPresent()) {
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(profilePicture.get().getPicture());
outputStream.close();
}
}
我使用VanillaJS和fetch-API发送GET请求:
async function downloadPicture(profilePic, studentId) {
const url = "http://localhost:8080/student/pic/" + studentId;
const response = await fetch(url);
const responseBlob = await response.blob();
if (responseBlob.size > 0) {
profilePic.src = URL.createObjectURL(responseBlob);
}
}
不知怎么的,这是可行的。这很好,但是现在我想了解HttpServletResponse
在这个上下文中的用法,这一点我并不熟悉。在我看来,fetch-API使用了HttpServletResponse (甚至可能创建它),因为我没有创建这个对象,也没有对它做任何事情。
对我来说非常奇怪的是,我的控制器方法getProfilePicture()
的返回类型是void
,而且我仍然在发送一个响应,这肯定不是无效的。
另外,如果在我的数据库中找不到profilePicture,例如由于一个不存在的studentId被传递,那么我的控制器-方法不会做任何事情。但是,我仍然得到了200的响应代码。这就是为什么我在我的Javascript中添加了responseBlob.size > 0
部分,以检查是否有积极的响应。
有人能给我解释一下这个魔法吗?
发布于 2022-01-04 12:19:21
response.getOutputStream();
javadoc说:“返回一个适合在响应中写入二进制数据的ServletOutputStream。”它实际上是响应流,您将图片字节写入其中。这与读取响应的客户端无关。或者,您只需返回一个字节数组,该数组将自动写入响应流,结果将是相同的。
若要返回不同的http状态代码,应将方法返回类型更改为ResponseEntity<byte[]>
@GetMapping("student/pic/studentId")
public ResponseEntity<byte[]> getProfilePicture(@PathVariable Long studentId, HttpServletResponse response) throws IOException {
Optional<ProfilePicture> profilePicture = profilePictureService.getProfilePictureByStudentId(studentId);
if (profilePicture.isPresent()) {
return ResponseEntity.ok(profilePicture.get().getPicture()); //status code 200
} else {
return ResponseEntity.notFound().build(); //status code 404
}
}
ResponseEntity基本上是返回不同状态代码/消息的springs方式。
您是否有理由通过javascript手动下载图像?您可以创建一个带有指向图像的http链接的img元素,浏览器将自动显示图像内容:<img src="http://localhost:8080/student/pic/studentId">
。
https://stackoverflow.com/questions/70577024
复制相似问题