Search code examples
javascriptnode.jsimagemultersharp

How to download processed image from buffer in Sharp


I am taking input image using Multer into buffer multer.memoryStorage(), now I am using Sharp to change format and again sending it to buffer using .toBuffer(). I've got it to work until this part. Now I want to download this processed image in buffer when user clicks a button. Any ideas on how to do this ?

Here is my ejs file

<form method="post" action="upload" enctype="multipart/form-data">
    <input name="image" type="file">

    <div>
        <label for="format">Select format</label>   
        <select id="format" name="format">
            <option value = "png">PNG</option> 
            <option value = "jpeg">JPEG</option>
        </select>

        <button id="submit" type="submit">Submit</button>
        <button id="download">Download</button>
    </div>
</form>

Here is my server.js file

const storage = multer.memoryStorage();
const upload = multer({storage: storage});
app.post("/upload", upload.single('image'), (req, res) => {
    (async ()=> {
        try {
            const {data, info} = await sharp(req.file.buffer)
            .withMetadata()
            .toFormat(req.body.format)
            .toBuffer({resolveWithObject: true});
        
            console.log(data, info);
        } catch(error) {
            console.log(error);
        }
    })()
});

There should be a prompt to download the processed image when the user clicks on 'Download' button. Thanks in advance


Solution

  • You should not use sharp npm. You should use multer-sharp-s3 npm which does the work. Research the github documentary which is on this link.