Hello. I am trying to integrate the services to upload and store the images Directly with Next Js (pages). I was following the docs but still having errors and the docs doesn’t show me anything else about how to handle it.
import type { NextApiRequest, NextApiResponse } from 'next'
import formidable from 'formidable'
import fs from 'fs'
import axios from 'axios'
const formFormidable = formidable({ multiples: true })
export const config = {
api: {
bodyParser: false,
},
}
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'POST') {
return res.status(405).json({ message: 'Method not allowed' })
}
try {
const fileContent: string = await new Promise((resolve, reject) => {
formFormidable.parse(req, (err, _fields, files) => {
if (!files.file) {
return res.status(400).json({ message: 'File not found' })
}
const fileContentBuffer = fs.readFileSync(files.file[0].filepath)
const fileContentReadable = fileContentBuffer.toString('utf8')
resolve(fileContentReadable)
reject()
})
})
const form = new FormData()
form.append('file', fileContent)
const options = {
method: 'POST',
url: `https://api.cloudflare.com/client/v4/accounts/${process.env.ACCOUNT_ID_CLOUDFLARE}/images/v1`,
headers: {
'Content-Type': 'multipart/form-data',
Authorization: `Bearer ${process.env.API_TOKEN_CLOUDFLARE}`,
},
data: '[form]',
}
const result = await axios.request(options)
if (result.data) {
console.log(result)
res.status(200).send({ message: 'Ok' })
} else {
res.status(400).send({ message: 'Failed to upload image' })
}
} catch (err) {
if (err instanceof Error) {
res.status(400).send({ message: err.message })
} else {
res.status(400).send({ message: 'Bad Request' })
}
}
}
response: “Request failed with status code 400”
if I change the option to this:
const options = {
/// ...same options,
data: [form],
}
response: “source.on is not a function”
If I change the option to this:
const options = {
/// ...same options,
data: form,
}
Response: “Request failed with status code 415”
How can I upload images with api next js?