MongoDB의 이미지 파일에 액세스하고 Express.js를 사용하여 클라이언트로 보내는 방법

Aug 18 2020

mongoose를 사용하여 MongoDB에 일부 이미지 파일을 저장했습니다. 이미지는 HTML 양식에서 제출 된 다음 Express POST 요청을 통해 MongoDB로 전송됩니다. 그런 다음 GET 요청을 통해 MongoDB의 해당 이미지 파일에 액세스 한 다음 클라이언트 측으로 전송하고 싶습니다. 이에 대한 코드는 다음과 같습니다.

app.get("/showallimages", (req, res) => {

    Image.find({}).exec((error, records) => { // Image is the database schema model. 

        var img1 = Buffer.from(records[0].img.data, "base64"); // First image coming from MongoDB.
        var img2 = Buffer.from(records[1].img.data, "base64"); // Second image coming from MongoDB.
        var images = [img1, img2];

        res.writeHead(200, {
            "Content-Type": "image/png",
        })

        var i = 0;
        for (i; i <= images.length; i++) {
            res.end(images[i]); // I am expecting this to send both images to the client side, but instead I am only getting the first image to be displayed. 
        }

    })

})

"이미지"를 console.log하면 두 파일의 이진 데이터를 얻습니다.

console.log(images); 

  <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 02 00 00 64 00 64 00 00 ff ec 00 11 44 75 63 
6b 79 00 01 00 04 00 00 00 22 00 00 ff ee 00 0e 41 64 6f 62 65 00 64 ... 8728 more bytes>,
  <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 05 39 00 00 03 84 08 06 00 
00 00 6a f3 35 f1 00 00 00 01 73 52 47 42 00 ae ce 1c e9 00 00 00 f2 ... 397757 more bytes>

나는 이것이 두 이미지를 클라이언트 측에 보낼 것으로 기대하고 있지만 대신 첫 번째 이미지 만 표시됩니다.

이 프로세스에서 두 개 이상의 파일을 보낼 수있는 방법에 대한 설명을 주시면 감사하겠습니다. 또한이 작업을 수행하는 올바른 방법을 선택하고 있는지 알려주십시오.

감사!

답변

1 Victor_Maciel Aug 20 2020 at 19:16

코드에 논리 오류가 있습니다. res.end ()가 호출되면 express는 첫 번째 이미지에서 응답 프로세스를 종료하고 루프는 다음 반복에 도달하지 않습니다. 또한 하나의 요청에 대해 여러 응답을 가질 수 없습니다. 그러나을 사용하여 JSON 표현으로 버퍼 배열을 보낼 수 있습니다 res.json(images).

클라이언트 에서 서버에서 버퍼로받은 이미지를 표시하려면 다음을 수행하여 원본 형식으로 변환해야합니다.

// server response
const images = response.map(buffer => {
  const rawBuffer = buffer.toString("base64");
  const imageSrc = "data:image/png;base64," + rawBuffer;
  const image = document.createElemment("img");
  image.src = imageSrc;
  return image;
})

/* 
In this method you can control how you will show the images in the client 
(to test, just append to any div)
*/

또는 조작없이 이미지를 표시하려면 다음을 시도하십시오.

app.get("/showallimages", (req, res) => {

    Image.find({}).exec((error, records) => { // Image is the database schema model. 

        var img1 = Buffer.from(records[0].img.data, "base64"); // First image coming from MongoDB.
        var img2 = Buffer.from(records[1].img.data, "base64"); // Second image coming from MongoDB.
        var images = [img1, img2];

        const formatedImages = images.map(buffer => {
          return `<img src="data:image/png;base64,${buffer.toString("base64")}"/>`
        }).join("")
        
        res.send(formatedImages)

    })

})