I have been trying to upload pdfs and save it in backend using multer in next js. now the payload does go to backend
but the problem is it doesnt store file in public/uploads. In fact I'm unable to access it at all.
here undefined is me trying to access file and above it is a error .
that being said if I console log req.body i get this
what do i do to
- access file from backend
- store it in 'public/uploads'
import React, { useState } from 'react';
const FileUploader = () => {
const [file, setFile] = useState(null);
const handleChange = (event) => {
setFile(event.target.files[0]);
console.log(event.target.files[0]);
};
const handleUpload = async (event) => {
event.preventDefault();
if (!file) {
alert('Please select a file before uploading.');
return;
}
try {
const formData = new FormData();
formData.append('file', file);
const response = await fetch('/api/hello', {
method: 'POST',
body: formData,
});
if (response.ok) {
alert('File uploaded successfully!');
} else {
alert('Failed to upload the file. Please try again.');
}
} catch (error) {
console.error('Error uploading the file:', error);
}
};
return (
<form encType="multipart/form-data" method="post">
<input
type="file"
name="file"
accept="application/pdf"
onChange={handleChange}
/>
<input type="submit" value="Upload" onClick={handleUpload} />
</form>
);
};
export default FileUploader;
this is my frontend code
import multer from 'multer';
const upload=()=>multer({
storage: multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './public/uploads')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
})
})
export default function handler(req, res) {
upload().single('file')(req, res, function (err) {
if (err instanceof multer.MulterError) {
console.log(err)
} else if (err) {
console.log(err)
}
console.log(req.file)
})
res.status(200).json({ name: 'John Doe' })
}
this is my backend code
if i add
'Content-Type': 'multipart/form-data',
},
as mentioned in one of answers I was searching ( in chatgpt ). I'll get a diffrent error saying Multipart: Boundary not found.
I have also tried watching this youtube channel youtube but also tried to see other channels. the downside is they are telling how to solve in node js and for next js there aren't many resources I could find