0

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);
    })
Harzzshest
  • 67
  • 2
  • 9

1 Answers1

0

You will need to append your Image file that you are sending to the JSON Request body.

You can refere to this post here:

Javascript: Upload File

C Rishi
  • 216
  • 1
  • 5
  • Even if I change the Axios to fetch and do it as you say... ` fetch(`${HOST}/books/${books_id}/upload`, { method: 'POST', headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }, body: data })` ... still does the exact same thing.. File gets transported but its size 0 as if there is no content coming with it – Harzzshest May 14 '21 at 15:40
  • 1
    Try logging the file on the backend and let us know what it prints. – Charchit Kapoor May 14 '21 at 15:43
  • that's what file prints on backend `{ fieldname: 'file', originalname: 'nineteen-eighty-four.jpg', encoding: '7bit', mimetype: 'image/jpeg', buffer: , size: 284833 } ` I'm guessing it's missing stuff like temporary path and stream but i have no idea why.. – Harzzshest May 14 '21 at 15:47