I'm trying to successfully upload a file (image) but something goes wrong because the file appears to get moved to the correct directory but it's of size 0 as if it doesn't actually have any content and when I try to open it.. it fails. I think I might be missing "stream" because when i console.log the file on the backend there is no stream property.. and I also get an error in the console saying "The "source" argument must be of type function or an instance of Stream, Iterable, or AsyncIterable. Received undefined"
My front end:
const UploadPoster = ({books_id}) => {
const [file, setFile] = useState();
const send = () => {
const data = new FormData();
data.append('file', file);
Axios.post(`${HOST}/books/${books_id}/upload`, data, {
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`
},
})
.then(res => console.log(res))
.catch(err => console.log(err));
history.go(0)
};
const history = useHistory();
return (
<>
<form action="#">
<div className="flex">
<label htmlFor="file">Update book cover:</label>
<input type="file" id="file" onChange={event => {
const file = event.target.files[0];
setFile(file);
}} />
</div>
</form>
<Button onClick={send}>Upload</Button>
</>
)
}
My backend:
.post('/:id/upload', authMiddleware, loggedUserGuard, roleMiddleware(userRole.Admin), upload.single('file'), async (req, res) => {
const {file} = req;
await pipeline(
file.stream,
fs.createWriteStream(`${__dirname}/../../../front_end/public/posters/${req.file.originalname}`),
);
res.send('File uploaded as ' + req.file.originalname);
})