Skip to content

Commit

Permalink
feat: upload images to s3
Browse files Browse the repository at this point in the history
  • Loading branch information
betich committed Apr 14, 2023
1 parent d292ef7 commit e76347f
Show file tree
Hide file tree
Showing 5 changed files with 212 additions and 10 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"fix:prettier": "pnpm lint:prettier --write"
},
"dependencies": {
"aws-sdk": "^2.1358.0",
"clsx": "^1.2.1",
"next": "^12.1.6",
"next-pwa": "^5.5.4",
Expand Down
152 changes: 152 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 0 additions & 9 deletions src/pages/api/hello.ts

This file was deleted.

40 changes: 40 additions & 0 deletions src/pages/api/upload.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import type { NextApiRequest, NextApiResponse } from "next"

import AWS from "aws-sdk"

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
// data is in base64
const { good, data: base64Data } = JSON.parse(req.body)

// convert base64 to buffer
const imgData = Buffer.from(base64Data.replace(/^data:image\/\w+;base64,/, ""), "base64")

// upload to S3
const s3 = new AWS.S3({
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
})

const filename = new Date().toISOString()

const type = base64Data.split(";")[0].split("/")[1]

const params: AWS.S3.PutObjectRequest = {
Bucket: process.env?.AWS_BUCKET_NAME ?? "",
Key: `${good ? "good" : "bad"}-${filename}.${type}`,
Body: imgData,
ACL: "public-read",
ContentEncoding: "base64", // required
ContentType: `image/${type}`, // required. Notice the back ticks
}

s3.upload(params, (err: any, data: any) => {
if (err) {
console.error(err)
res.status(500).json({ error: err })
} else {
console.log(data.Location)
res.status(200).json({ name: data.Location })
}
})
}
20 changes: 19 additions & 1 deletion src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,25 @@ export default function HomePage() {
canvasRef?.current
?.exportImage("png")
.then((data) => {
console.log(data)
// post to api route /upload
fetch("/api/upload", {
method: "POST",
body: JSON.stringify({
good: isGood,
data,
}),
})
.then((res) => {
if (res.status === 200) {
console.log("Success")
}
})
.catch((e) => {
console.error("Error", e)
})
.finally(() => {
canvasRef?.current?.clearCanvas()
})
})
.catch((e) => {
console.log(e)
Expand Down

0 comments on commit e76347f

Please sign in to comment.