'Can't upload images to strapi via next.js api route
I have a complex form with a few file uploads, and I made it using react-hook-form with react-dropzone for file upload, data from the form is stored in react context.
Now at the last step of the form, I load data from react-context and I'm sending it to Strapi CMS via next.js API routes, and everything except file upload works fine. I always get error 500, but from the Altair client, I can upload it normally.
files data than I'm sending looks (logo in the code bellow):
upload files next.js api route:
const fRes = await api.upload('api/upload-files', data.logo)
api.upload:
async upload(endpoint: string, body) {
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
},
body: JSON.stringify(body),
})
if (!response.ok) {
throw new Error(`Error: ${response.status}`)
}
const res = await response.json()
return res
}
pages/api/upload-files:
import { NextApiRequest, NextApiResponse } from 'next'
import { apolloClient } from 'lib/apolloClient'
import { UPLOAD_FILES_MUTATION } from 'lib/models/Registration'
export default async (req: NextApiRequest, res: NextApiResponse) => {
console.log(req.body)
const { errors, data } = await apolloClient.mutate({
mutation: UPLOAD_FILES_MUTATION,
variables: { files: req.body },
})
if (errors) {
return res.status(400).json(errors)
}
return res.status(200).json(data)
}
graphql mutation:
mutation ($files: [Upload]!) {
multipleUpload(files: $files) {
data {
id
attributes {
name
}
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

