首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在为BLOB发出GET请求时,HttpServletResponse是如何与fetch API纠缠的?

在为BLOB发出GET请求时,HttpServletResponse是如何与fetch API纠缠的?
EN

Stack Overflow用户
提问于 2022-01-04 10:03:46
回答 1查看 75关注 0票数 0

使用Spring,我尝试实现一个REST控制器,它可以处理请求从数据库返回BLOB对象的GET请求。

我在谷歌上搜索了一下,并将代码片段拼凑在一起,创建了以下代码片段:

代码语言:javascript
运行
复制
@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请求:

代码语言:javascript
运行
复制
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部分,以检查是否有积极的响应。

有人能给我解释一下这个魔法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-04 12:19:21

response.getOutputStream(); javadoc说:“返回一个适合在响应中写入二进制数据的ServletOutputStream。”它实际上是响应流,您将图片字节写入其中。这与读取响应的客户端无关。或者,您只需返回一个字节数组,该数组将自动写入响应流,结果将是相同的。

若要返回不同的http状态代码,应将方法返回类型更改为ResponseEntity<byte[]>

代码语言:javascript
运行
复制
@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">

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70577024

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档