This commit is contained in:
tonyrewin 2022-12-21 08:40:26 +03:00
parent d9dfd61d50
commit 02b654917b

View File

@ -1,8 +1,20 @@
// pages/api/upload.ts // pages/api/upload.ts
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3' import { S3Client, PutObjectCommand, PutObjectCommandInput } from '@aws-sdk/client-s3'
import { createPresignedPost } from '@aws-sdk/s3-presigned-post' import { createPresignedPost } from '@aws-sdk/s3-presigned-post'
export async function putToS3(fileObject, presignedUrl) {
const requestOptions = {
method: 'PUT',
headers: {
'Content-Type': fileObject.type
},
body: fileObject
}
const response = await fetch(presignedUrl, requestOptions)
return await response
}
export default async function handler(req, res) { export default async function handler(req, res) {
const s3Client = new S3Client({ const s3Client = new S3Client({
region: process.env.S3_REGION || 'eu-west-1', region: process.env.S3_REGION || 'eu-west-1',
@ -11,8 +23,7 @@ export default async function handler(req, res) {
secretAccessKey: process.env.S3_SECRET_KEY secretAccessKey: process.env.S3_SECRET_KEY
} }
}) })
const presignedUrl = await createPresignedPost(s3Client, {
const post = await createPresignedPost(s3Client, {
Bucket: process.env.S3_BUCKET_NAME || 'discours-io', Bucket: process.env.S3_BUCKET_NAME || 'discours-io',
Key: req.query.file, Key: req.query.file,
Fields: { Fields: {
@ -24,6 +35,7 @@ export default async function handler(req, res) {
['content-length-range', 0, 22 * 1048576] // up to 22 MB ['content-length-range', 0, 22 * 1048576] // up to 22 MB
] ]
}) })
const result = await putToS3(req.query.file, presignedUrl)
res.status(200).json(post) console.debug(result)
res.status(200).json(presignedUrl)
} }