catalystbyzohozohocatalystcatalystcloudscale

How to display Image file from Catalyst Filestore in my HTML page?


I am trying to build a gallery application using Catalyst Web Client Hosting where I need to display the images stored in my Filestore in my web app. I tried using the URL from getDownloadLink() Web SDK method to display the image in the img tag which doesn't seem to work.

Can someone help me provide a workaround solution for my use-case?


Solution

  • The URL from the getDownloadLink() method will return the file as attachment so you won't be able to display the file in the image tag. To display the image from img tag you would need to download the file using a Catalyst advanced I/O function and send the file object in the response. You can use the function URL endpoint in your img src.

    You can find a sample catalyst node function performing the same below:

    'use strict';
    var express = require('express');
    var app = express();
    var catalyst = require('zcatalyst-sdk-node');
    
    app.use(express.json());
    
    app.get('/url:id', async (req, res) => {
        const capp = catalyst.initialize();
        const fileid = req.params.id;
        let filename = (req.query.filename)
        let filestore = capp.filestore();
        let foldere = filestore.folder('<YOUR_FOLDER_ID>');
            try {
                const fileBuffer = await foldere.downloadFile(`${fileid}`);
                console.log('fileBuffer:', fileBuffer, 'Type: ', typeof (fileBuffer));
                if (fileBuffer) {
                    res.writeHead(200, { 'Content-Type': 'image/png' });
                    res.end(fileBuffer);
                } else {
                    res.status(500).send('Cannot send File');
                }
            } catch (error) {
                res.status(500).send(error)
            }
        }
    )
    
    module.exports = app;
    

    You can send the File ID from the client JS to the function URL.