#Can anyone show me an example of uploading an image using a handler function?
7 messages · Page 1 of 1 (latest)
I am not very experienced with file uploads, especially using AWS S3. I read the documentation, but I am still a bit confused. I implemented it as follows.
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
const s3Client = new S3Client({})
export const handler: Handler = async (event, context) => {
const productId = randomUUID()
const { description, price, base_64_file, segments_ids } = event.arguments as Schema['customCreateProduct']['args']
const image = base64ToStreamingBlob(base_64_file)
const productTransactItem: TransactWriteItem = {
Put: {
....
},
}
const productSegmentTrasactItems: TransactWriteItem[] = segments_ids.map(segmentId => {
return {
.....
}
}
})
const transactionObject = new TransactWriteItemsCommand({
TransactItems: [
productTransactItem,
...productSegmentTrasactItems
]
})
const command = new PutObjectCommand({
Bucket: '...',
Key: '123',
ContentType: 'image/webp',
Body: image.stream,
})
await docClient.send(transactionObject)
await s3Client.send(command)
}
Response error:
[
{
path: [ 'customCreateProduct' ],
data: null,
errorType: 'Lambda:Unhandled',
errorInfo: null,
locations: [ [Object] ],
message: 'A header you provided implies functionality that is not implemented'
}
]
Remember that using an api may not be ideal due to the size limit and timeout for a Lambda function.
Actually, I do have an example to share. Take a look at the handleFileSelect function here: https://github.com/onyxdevtutorials/vite-amplify-v6-react-tutorial/blob/main/src/components/ProductForm.tsx This project used Gen 1 but I think it's still relevant. I made it to accompany an article I wrote: https://medium.com/@davidavilasilva/getting-started-with-vite-vitest-aws-amplify-and-react-12b7ed337a93
Hey @autumn wadi , are you using the handler function because you need to (1) control the file name of the uploaded file and (2) create a DynamoDB item to accompany it?
There's another approach you could take:
1. Create the DynamoDB item using a lambda handler. Generate a pre-signed upload url (which defines the file name and path) and return it as `Item.uploadUrl`. Authorize only the owner to access this attribute.
2. The client side uses the uploadUrl to perform a simple upload.
3. (optional) An S3 onCreate handler updates the DynamoDB entry when the file is uploaded to remove the uploadUrl and a flag to indicate that the file was uploaded successfully.
Thank you for trying to help. I see that your example uses uploadData, but what I need to do is execute image upload on the server side to validate it correctly. My application is using next.js and I send a request to a server action that send a request to my lambda function.