Skip to content

Instantly share code, notes, and snippets.

@0xmovses
Last active December 22, 2021 14:17
Show Gist options
  • Save 0xmovses/78f386a15654b451532f8a0a0ff26d50 to your computer and use it in GitHub Desktop.
Save 0xmovses/78f386a15654b451532f8a0a0ff26d50 to your computer and use it in GitHub Desktop.
aws-next.js file upload unsignedpost
//client-side code
const formik = useFormik({
initialValues: {
username: '',
bio: '',
img: ''
},
onSubmit: async (values) => {
let data = new FormData();
data.append("artist_name", values.username);
data.append("bio", values.bio);
data.append("file", values.img);
data.append("admin_email", user.email);
const res :any = await createUnactivatedArtist(data);
const { url, fields } = res.data;
const file = values.img;
console.log({ file })
console.log({ fields })
const uploadForm = new FormData();
Object.entries({ ...fields, file }).forEach(([key, value]) => {
//@ts-ignore
uploadForm.append(key, value);
});
const upload = await fetch(url, {
method: 'POST',
body: uploadForm,
});
if(upload.ok){
console.log({ upload });
console.log('upload successfull');
} else {
console.error('upload failed');
}
},
})
//backend api route
export default unactivatedArtistHandler
.get(async (req: NextApiRequest, res: NextApiResponse) => {
const UnactivatedArtists = await UnactivatedArtist.find({})
res.status(200).json({ success: true, data: UnactivatedArtists })
})
.post(async (req: NextApiRequest, res: NextApiResponse) => {
try {
//parse form to get file Name
const form = await parseForm(req)
const fileName = encodeURI(form.files.file.name)
console.log(form.fields)
aws.config.update({
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
region: process.env.AWS_REGION,
signatureVersion: 'v4',
})
const s3 = new aws.S3()
const post = await s3.createPresignedPost({
Bucket: process.env.AWS_IMG_BUCKET,
Fields: {
key: fileName,
},
Expires: 60, // seconds
Conditions: [
['content-length-range', 0, 1048576], // up to 1 MB
],
})
await dbConnect()
const unactivatedArtist: IUnactivatedArtist = form.fields
const locationUrl =
'https://' +
process.env.AWS_IMG_BUCKET +
'.s3.' +
process.env.AWS_REGION +
'.amazonaws.com' +
'/' +
fileName
unactivatedArtist.profile_image_url = locationUrl
console.log({ unactivatedArtist });
await UnactivatedArtist.create(unactivatedArtist)
//send email to artist
await new Email(unactivatedArtist, '45612').sendMagicLink();
return res.status(200).json(post)
} catch (error) {
console.log(error)
res.status(400).json({ success: false, message: error })
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment