'How do I upload an MP3 held in state via Fetch to a Next.JS API Route?

I have a voice-recorder that records user-audio and stores it as state in a ReactJS component. When I pass the file to my API route it is recognised as a string and I don't seem to be able to upload it to AWS S3 correctly.

Here is the ReactJS button Handler:

  const [audioFile, setAudioFile] = useState(null)

  ...
  const submitVoiceMemo = async () => {
    console.log('this is the payload', audioFile)
    // the file is named 'audio.mp3'

    try {
      await fetch('/api/createVoiceMemo', {
        method: 'PUT',
        body: audioFile
      })
    } catch (error) {
      console.error(error)
    }
  }

However, when the file 'arrives' at the API Route it is a string and I don't know how to convert it back to an MP3:

module.exports = requireAuth(async (req, res) => {

    console.log(req.body) 
    // this prints 'characters' the to the console and is typeof string

I also can't seem to restructure req.body - if I try to console.log(req.body.audioFile) I get undefined.

How do I format the file so that I can upload it as an MP3 to AWS S3?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source