0

I'm building a webApp in MEVN stack (Mongo, Express, Vue, Node).

In my backend, I have a controller (./backend/controllers/screenshots.controller.js) downloading an image from an external REST API. The image (PNG) is downloaded in a directory called 'images' placed in the controllers directory.

controllers/images

screenshots.controller.js:

const path = require('path');
const axios = require('axios');
const fs = require('fs');

const downloadScreenshot = async(screenshotPath) => {
    let isDownloaded = false;

    const fileUrl = `https://myexternalapi.com/screenshot/${screenshotPath}`;
    const fileName = screenshotPath.split('/')[1]
    const downloadFolder = './images'

    if(!fs.existsSync(downloadFolder)){
        fs.mkdirSync(downloadFolder);
        console.log('Images directory created successfully.');
    }

    const localFilePath = path.resolve(__dirname, downloadFolder, fileName);

    try {
        const response = await axios({
                                        method: 'GET',
                                        url: fileUrl,
                                        responseType: 'stream',
                                });
        if(response.status === 200){
            isDownloaded = true;
        }
        
        await response.data.pipe(fs.createWriteStream(localFilePath));


    } catch (error) {
        
        console.log('Error occured while downloading screenshot... : ', error);

    }

    return { isDownloaded, fileName };
} 

const readScreenshot = async(req, res) => {
    try {
        const {isDownloaded, fileName} = await downloadScreenshot(req.body.temp);

        if(isDownloaded){

            console.log('__dirname + /images/ + fileName  : ', __dirname + '/images/' + fileName )

            res
                .status(200)
                .sendFile(fileName, {root : __dirname + '/images/'} );
              

        } else {
            res
                .status(500)
                .send({
                    message: 'No screenshot for this offer...'
                })
        }
    } catch (error) {
        console.log('Error occured while retrieving screenshot...', error)
            res
                .status(500)
                .send({ message: error });
    }
}

module.exports = {
    readScreenshot: readScreenshot,
}

I would like to display the required image in my Vue app. Thus, I created the following view: ReadScreenshot.vue

<template>
    <div>
        <img :src="img">
    </div>
</template>

<script>
import Screenshots from '../../services/screenshots.service'
export default {
    props: ['id'],
    data(){
        return {
            img: '',
        }
    },

    async mounted(){
        console.log(this.id)
        const temp = await Screenshots.readScreenshot({ temp: this.id });
        console.log(temp)
        this.img = temp.data
    }
}
</script>

Here is my screenshots.service.js script:

import api from '../../http-common';

export default new class ScreenshotsService {
    //Read Screenshot
    readScreenshot(screenshotName){
        return api.post('read/screenshot', screenshotName)
    }
}

Console.log(temp) is returning empty data. Console.log(temp)

In the screenshots.controller.js file, if I'm forcing the fileName with an existing one in the sendFile function, e.g. '2882LsgIXHOiXiOQ5MSv3R6v1hDijAdG5i756CdG5o7v527i5sS1XZgiXR6i1sSGj.png', I'm receiving a non empty data in my ReadScreenshot.vue .

console.log(temp)

Even if I'm receiving the data, the image is still not displayed...

How should I proceed, to get this right?

thks for your help

Henri
  • 1,571
  • 5
  • 23
  • 38
  • 1
    https://css-tricks.com/data-uris/ – first last Feb 11 '22 at 13:12
  • thanks a lot @firstlast . It worked! I also found this answer with the updated version of Buffer https://stackoverflow.com/questions/53305365/vuejs-load-image-from-nodejs-res-sendfile – Henri Feb 11 '22 at 14:13

0 Answers0