使用 Spring Boot,我正在嘗試實作一個 REST 控制器,它可以處理一個 GET 請求,要求從我的資料庫中回傳一個 BLOB 物件。
谷歌搜索了一下,并將各個部分放在一起,我創建了以下代碼片段:
@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 的回應代碼。這就是為什么我responseBlob.size > 0在我的 Javascript 中添加了該部分以檢查是否有積極回應。
有人可以向我解釋一下這個魔法嗎?
uj5u.com熱心網友回復:
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基本上是回傳不同狀態代碼/訊息的彈簧方式。
您是否有理由通過 javascript 手動下載影像?你可以創建一個帶有圖片的 http 鏈接的 img 元素,瀏覽器會自動顯示圖片內容:<img src="http://localhost:8080/student/pic/studentId">
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/407043.html
標籤:
