簡體   English   中英

如何使用來自 node.js 的響應圖像渲染我的 ejs 視圖

[英]How to render my ejs view with response image from node js

我正在使用 gridfs 和 mongoDB 以塊的形式存儲圖像。 每當用戶請求我的服務器時,只需通過管道發送一個簡化的圖像文件作為響應。

目前我的代碼如下所示:

const download = async (req, res)=>{
try{
const fileName = req.params.name

await mongoClient.connect();

const database = mongoClient.db(dbConfig.database)
const bucket = new GridFsBucket(database, { // required for important methods like openDownloadStream
  bucketName:dbConfig.imgBucket
})

const downloadStream = bucket.openDownloadStreamByName(fileName);

downloadStream.pipe(res) // it only displays an jpg/png image
// res.render("image") , I want to render this ejs page with a image in it and with some static content in it. I want to stream image
 } catch(err){
res.status(501).render("error",{error: err})
}}

我的 output 看起來像:我的代碼 output

它只呈現一個 jpg 文件,就像上面的鏈接是如何工作的一樣。 但我想做的是從響應 object 中獲取圖像,並用我的其他 html 元素渲染它。

看起來你試圖一次做太多。

您需要將所需的流圖像與模板的初始渲染分離。 在您的 tempalte 中包含一個帶有不同 api 的圖像標簽,圖像將從該標簽中變為 stream,結果將類似於您的示例。

假設您的圖片名為test.png ,您的服務器名為index.js ,而您的 ejs 模板名為index.ejs 模板(為了你的問題)可以非常簡單: index.ejs -->

<h1> stream that image below! </h1>
<image src="/image" hieght="200px" width="200px";/>

請注意此圖像的src - 這將在您的后端命中一個不同的 api,該圖像將 stream。

服務器index.js將如下所示 -->

var exp = require("express");
var fs = require("fs");
var app = exp();

app.set("view engine", "ejs");

app.get("/image", (req, res) => {
  const streamReadFile = fs.createReadStream("test.png");
  streamReadFile.pipe(res);
});

app.get("/", (req, res) => {
  res.render("index");
});

app.listen(8080, () => {
  console.log("listening on *:8080");
});

請注意,在此處將模板呈現為

app.get("/", (req, res) => {
  res.render("index");
});

模板圖像中的 src 然后向服務器發出請求,點擊/image路由,這會將 stream 所需圖像發送到您的 html

app.get("/image", (req, res) => {
  const streamReadFile = fs.createReadStream("test.png");
  streamReadFile.pipe(res);
});

這是上面示例的工作演示,其中您的圖像被流式傳輸到 ejs 模板。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM