Currently, I am working on a project utilizing Next.js and I am facing the task of uploading photos to a Bucket S3. In order to stay up-to-date with the latest technology, I have chosen to utilize the latest version (3) of AWS SDK for JavaScript.
After several challenges, I successfully uploaded my first photo to the bucket. However, when attempting to view the image, I encountered the following error:
https://i.sstatic.net/NZyZT.png
My objective is to obtain the URL to set as the src
attribute in the <img />
element. It appears that there may be a permission issue with my bucket. My question is: Is it feasible to utilize the GetObjectCommand to retrieve the resource using the key and save it as a Blob object, subsequently using URL.createObjectURL
to link the image in HTML?
I attempted the following code snippet:
const BUCKET = 'bucket'
const client = new S3Client({
region: 'us-east-1',
credentials: {
accessKeyId: 'accessKey',
secretAccessKey: 'secretKey'
}
})
const response = await client.send(new GetObjectCommand({
Bucket: BUCKET,
Key: 'folder/image.jpg'
}))
However, the variable response.Body
is of type ReadableStream
rather than a Blob
.
In my search for a solution on converting the ReadableStream
to a Blob
, none of the approaches I came across seemed to work. Many of them revolved around downloading the resource (to the machine), like this example in Node.js.
While not being a JavaScript expert, I acknowledge that I may be overlooking some important concepts regarding streams and blobs, for which I apologize.
My ultimate goal is to securely access the resource without making my bucket public (as I intend to use the same bucket for storing private files under a different key). Is my current approach flawed? Is there a way to achieve this, or perhaps a more effective solution to address my predicament?