[英]Parsing an HTTP response with Content-Type: image/jpeg
我目前正在開發我的第一個Web應用程序,我的任務是從數據庫加載圖像並將其發送到客戶端以進行顯示。 在服務器端,我會
res.setHeader('Content-Type', pic.mimetype);
res.sendFile(pic.path,{ root: __dirname });
請求已完成,並且在Firefox console
的“網絡”選項卡中,我看到了響應,其中帶有附加的圖像及其type(image/jpeg)
的小縮略圖-因此,圖像確實已發送。
問題是我不知道如何將客戶端響應中接收到的數據轉換為可以讀取的File對象或可以將img
標簽的src
設置為的路徑。 有人可以告訴我該怎么做嗎? 我似乎在任何地方都找不到我需要的東西。
這是我在客戶端上的代碼:
var formData = new FormData();
formData.append("myfile", file);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE && this.status == 200){
// I need some code here that will convert the response data to a File
// object or something that can eventually be displayed inside an HTML
//element.
document.dispatchEvent(new CustomEvent("displayImage", {'detail': xhr.responseText}));
}
};
xhr.open("PATCH","/picture",true);
xhr.send(formData);
解決了! 顯然,只要將圖像的src設置為某個URL,就會執行GET請求。 因此,為了檢索所需的圖像,只需確保您具有與服務器端src中的URL具有相同URL的GET路由。 這樣,圖像將被自動檢索並顯示。 例如,如果圖像位於/ images中,則將src和GET路由URL都設置為“ / images”,然后在route方法中,檢索文件並將其作為響應發送。 將響應發送回客戶端時,請不要忘記將標題內容設置為圖像的mime類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.