I am trying to upload a base64 file to Pinata, but my Formdata seems malformed for unknown reason.
I create the formdata in index.js and send to the NextJS api as so:
// file is a base64 string
_createNFTFormDataFile = async (name, description, file) => {
try {
const formData = new FormData()
formData.append('name', name)
formData.append('description', description)
formData.append('file', file)
// formdata logs correctly
for (let pair of formData.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
const { data } = await axios.post('/api/upload', formData, {
headers: { 'Content-Type': 'multipart/form-data' }
})
} catch (ex) {
console.error(ex)
}
}
The call goes through page/api/middleware/middleware.js
import nextConnect from 'next-connect'
import multiparty from 'multiparty'
const middleware = nextConnect()
middleware.use((req, res, next) => {
const form = new multiparty.Form()
form.parse(req, function (err, fields, files) {
if (err) {
console.log(err)
next()
}
req.body = fields
req.files = files
next()
})
})
export default middleware
And then is passed to the handler in ./page/api/upload.js.
handler.post(async function handlePost ({ body, files }, response) {
try {
const fileUrl = await uploadFileToIPFS(files.file[0]) //
const metadata = {
name: body.name[0],
description: body.description[0],
image: fileUrl
}
const metadaUrl = await uploadJsonToIPFS(metadata, body.name[0])
return response.status(200).json({
url: metadaUrl
})
} catch (error) {
console.log('Error uploading file: ', error)
}
})
However, i can't retrieve the files here and get this error Error uploading file: TypeError: Cannot read properties of undefined (reading '0').
console.log(body, files) here gives: {"undefined":["[object Promise]"]} {}`.
Why can't I retrieve the formdata here?