簡體   English   中英

使用 multer 上傳文件后端快遞和前端反應缺少 stream 屬性

[英]Uploading file backend express and frontend react using multer missing stream property

我正在嘗試成功上傳文件(圖像),但出現問題,因為文件似乎已移動到正確的目錄,但它的大小為 0,好像它實際上沒有任何內容,當我嘗試打開它時。 。 它失敗。 我想我可能缺少“流”,因為當我 console.log 后端上的文件時沒有 stream 屬性..我還在控制台中收到錯誤消息“源”參數必須是 function 類型或Stream、Iterable 或 AsyncIterable 的實例。收到未定義“

我的前端:

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>
    </>
  )
}

我的后端:

    .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);
    })

您將需要 append 您發送到 JSON 請求正文的圖像文件。

你可以在這里參考這篇文章:

Javascript:上傳文件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM