Answer the question
In order to leave comments, you need to log in
Getting an empty array of files on the server?
I take files from the client and put them in FormData, after which I send them to the server, but on the server I get an empty
photos.ts array:
export const config = {
api: {
bodyParser: true
}
}
const storage = multer.diskStorage({
destination:(req, file, cb) => {
cb(null, "public/uploads/photos")
},
filename:(req, file, cb) => {
cb(null, file.fieldname + "-" + Date.now() + path.extname(file.originalname))
}
})
const uploadImages = multer({ storage, limits: { fieldSize: 25 * 1024 * 1024 } });
const uploadPhotos = uploadImages.any("photos");
handler.use(uploadPhotos);
export default handler.post(async(req:any, res:NextApiResponse) => {
try {
console.log(req.files) // []
res.status(200).json({ success: true });
} catch(e) {
console.log(e);
res.status(500).json({
success: false, message: "Ошибка сервера"
})
}
})
const addPhotosHandler = async(event) => {
if (!event.target.files?.length) return;
const formData = new FormData();
for (let i = 0; i < event.target.files.length; i++) {
formData.append("photos", event.target.files[i]);
}
const response = axios.post(`${process.env.API_URL}/api/upload/photos`, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
response.then((res:any) => {
setActive(false);
console.log(res.data); // { success: true }
}).catch(err => {
setInfo({
type: "error",
text: `Ошибка сервера: ${err.message}`
})
})
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question