I've built a NextJS React app that uploads audio in MP3 format to an AWS S3 bucket. I have tested my API Route with a simple HTML file upload component... and it works!
When I try to upload audio created in the browser however, I receive a 400 Bad Request Error for the POST Request, so I think that my Javascript browser-record-upload component is problematic. It doesn't throw any errors however, but successful upload fails.
Here is the component:
const submitVoiceMemo = async () => {
console.log('this is the payload', audioFile)
// audioFile is an .mp3 file that is held in state once the recording is completed
const filename = encodeURIComponent(audioFile.name)
console.log('this is the filename:', filename)
const res = await fetch(`/api/upload-url?file=${filename}`)
console.log('This is the res: ', res)
const { url, fields } = await res.json()
const formData = new FormData()
Object.entries({ ...fields, audioFile }).forEach(([key, value]) => {
formData.append(key, value)
})
console.log("This is the formData: ", ...formData)
const upload = await fetch(url, {
method: 'POST',
body: formData
})
console.log("This is the upload: ", upload)
// This returns a 400 error and the response below is upload failed.
if (upload.ok) {
console.log('Uploaded successfully!')
} else {
console.error('Upload failed.')
}
}
Like I said, with a simple HTML file-upload component, the API works, so I think the problem is with the React component, and not the API. Nevertheless, here is the API for completeness:
module.exports = async (req, res) => {
try {
aws.config.update({
accessKeyId: process.env.AWS_ACCESS_KEY_1,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY_ID,
region: 'us-east-2',
signatureVersion: 'v4'
})
const s3 = new aws.S3()
const post = await s3.createPresignedPost({
Bucket: 'waveforms',
Fields: {
key: `voicememo/${req.query.file}`,
ACL: 'public-read',
ContentType: 'audio/mpeg'
}
})
console.log('This is the Post: ', post)
res.status(200).json(post)
} catch (e) {
res.status(500).json({ error: e.message })
}
}