I have a NextJS app with a form in which the user has to upload an image. This form sends a request to an API Route. In the API Route, I send the fields and the image to the API in Django, but I get this error: The submitted data was not a file. Check the encoding type on the form.
. The image (path) is an ImageField, and I am using the default post
method from ModelViewSet
. I assume it is not an error in the DRF API, as I uploaded images using the the form-data
tab in Postman and using with Python requests
library.
In the API Route, I have this code:
...
export default async (req, res) => {
if (req.method === 'POST') {
const cookies = cookie.parse(req.headers.cookie ?? '');
const access = cookies.access ?? false;
if (access === false) {
return res.status(401).json({
error: 'Usuario no autorizado para crear imágenes'
});
}
const form = new formidable.IncomingForm();
const formData = await new Promise((resolve, reject) => {
form.parse(req, (err, fields, files) => {
if (err)reject(err);
resolve({ fields, files });
});
});
const { path } = formData.files;
const { nombre, tema } = formData.fields;
console.log(path); // PersistentFile { ... }
const newFormData = new FormData();
newFormData.append('path', path);
newFormData.append('nombre', nombre);
newFormData.append('tema', tema);
try {
const apiRes = await fetch(`${API_URL}/preguntas/imagenes/`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Authorization': `Bearer ${access}`,
},
body: newFormData
});
const data = await apiRes.json();
...
};
export const config = {
api: {
bodyParser: false,
},
};
After adding config
, it seems like I can get all the information submitted in the form (the fields and the image), but when I post the information in the API I get the previous error. console.log(path)
prints the image as a PersistentFile
. My question is: How can I fix this? Do I have to transform the image before sending the request to the DRF API?
I tried to transform the image into a blob, but I couldn't fix it. If I write something like this:
...
newFormData.append('path', path.path, path.name);
...
The error I get is Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'
, so I think the problem is that I have to transform the PersistentFile
into a Blob
, but I don't know how.