Created
December 23, 2021 17:37
-
-
Save ChaseH88/4184c4108edab61c102efab4821cf985 to your computer and use it in GitHub Desktop.
S3 File Upload with AWS SDK (with custom metadata)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import dotenv from 'dotenv'; | |
dotenv.config(); | |
import type { NextApiRequest, NextApiResponse } from 'next'; | |
import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; | |
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3"; | |
interface PresignedURLResponse { | |
success: boolean, | |
data: string | |
} | |
/** | |
* | |
* @param req | |
* @param res | |
* @url /api/claims/files/presigned-url?name=<FILENAME.EXT>&id=<CLAIMID> | |
*/ | |
const handler = async ({ query, headers }: NextApiRequest, res: NextApiResponse<PresignedURLResponse>) => { | |
try { | |
if (!query?.name || !query.id) { | |
throw new Error(); | |
} | |
const client = new S3Client({ | |
region: process.env.AWS_REGION, | |
credentials: { | |
accessKeyId: process.env.AWS_ACCESS_KEY!, | |
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY! | |
} | |
}); | |
const command = new PutObjectCommand({ | |
Bucket: process.env.AWS_BUCKET_NAME, | |
Key: `${query.id}/${query.name}`, | |
Metadata: { | |
'tags': query.tags as string | |
} | |
}); | |
const url = await getSignedUrl(client, command, { | |
expiresIn: 60/**secs*/ * 15/**mins*/ | |
}); | |
res.status(200).json({ | |
success: true, | |
data: url | |
}); | |
} | |
catch (err) { | |
res.status(500).json({ | |
success: false, | |
data: 'Error, something went wrong.' | |
}); | |
} | |
} | |
export default handler; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment