In NextJS, I have am passing event.target.files into upload.js. To do this, I am using Axios:
const formData = new FormData()
for (let i = 0; i < formFiles.length; i++) {
formData.append('files[]', formFiles[i])
}
const response = await axios.post("/api/upload", formData, {
headers: {"content-type": "multipart/form-data"},
onUploadProgress: (progressEvent) => {
const percentage = (progressEvent.loaded * 100) / progressEvent.total;
console.log(percentage)
setProgress(+percentage.toFixed(2));
},
})
In Upload.js, I pass the formdata like so:
const parseFormData = (request) => {
return new Promise((resolve, reject) => {
const form = new formidable.IncomingForm({
multiples: true,
keepExtensions: true,
});
form.parse(request, (err, fields, files) => {
if (err) {
console.log("Form error: " + err)
reject(err);
}
resolve({ fields, files });
});
});
};
export default async function handler(request, response) {
if (request.method === "POST") {
const { files } = await parseFormData(request);
const formFiles = files['files[]']
console.log(formFiles)
if(formFiles instanceOf Array) {
...
However if formFiles is a single file then it only passes the one file through, but it doesnt register as an array. If I pass multiple files through, then it works fine with
formFiles instanceOf Array. But if there's only one file this fails. How can I accurately determine if theres one file, multiple, or none passed (Error~?)