MERN Stack - Download file from Amazon s3 using @aws-sdk/client-s3 & @aws-sdk/s3-request-presigner

Viewed 10

I am trying to download an image from Amazon s3 using the @aws-sdk/client-s3 package. The image will download but I can't open it. I get an error and says it is an unrecognizable format.

React Component Download Function

const downloadImg = (e) => {
    const href = e.target.getAttribute('img-data');
    var img = href.split('/').pop();

    const options = {
        method: 'GET',
        headers: { "Authorization" : `Bearer ${token}` },
    };

    fetch(`/download-img/${img}`, options)
    .then(response => response.blob())
    .then(blob => { 
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = img;
        document.body.appendChild(a);
        a.click();  
        a.remove();
    });
}

Node/Express Route


//  @desc   Download Screenshot
//  @route  get /download-img
//  @access Private
app.get('/download-img/:id', authenticateToken, async(req, res) => {
    const imgUrl = req.params.id;

    try {
        const getObjectParams = {
            Bucket: awsBucketName,
            Key: imgUrl,
        }

        const command = new GetObjectCommand(getObjectParams);
        const file = await getSignedUrl(s3, command, {expiresIn: 60});

        const img = axios.get(file)
        .then(function (response) {  
            res.send(response.data)
          })
        .catch(function (error) {
            // handle error
            console.log(error);
        })
        
    } catch (err) {
        console.log(err)
    }
});

Response.data Output

Output in node.js from response.data

0 Answers
Related