首页 > 解决方案 > 在 express/multer 中读取 CSV 文件而不将文件保存在服务器上

问题描述

我目前有一个带有反应前端的快速服务器,我设法使用它从前端发送一个 csv 文件到后端

onClickHandler = async e => {
    e.preventDefault();
    const data = new FormData()
    data.append('file',this.state.selectedFile)
   Axios.post("/api/upload",data)
   .then(res => console.log(res))
   .catch(err => console.log(err));
    
  }

(FormData 保存我的 CSV 文件)

但是在快递中,我正在使用 multer 来接收这个

const upload = multer()
app.post('/api/upload', upload.single("file"), (req, res) => {
  console.log(req.body)
  
 
});

当我控制台记录“req”时,我得到了这个:

fieldname: 'file',
[0]     originalname: 'test1.csv',
[0]     encoding: '7bit',
[0]     mimetype: 'application/vnd.ms-excel',
[0]     buffer: <Buffer 41 63 63 6f 75 6e 74 4e 61 6d 65 2c 41 63 63 6f 75 6e 74 56 61 6c 75 65 0d 0a 50 45 54 54 59 20 43 41 53 48 2c 31 37 32 36 39 2e 35 31 0d 0a 43 41 53 ... 
381 more bytes>,

我知道我正在发送一个缓冲区对象,但是我想访问内容并最终验证文件的列和行,但是我搜索的所有内容都是关于首先保存文件,这是我不想做的。我只想访问它而不保存到服务器。

任何帮助,将不胜感激。

标签: node.jsreactjsexpresshttpmulter

解决方案


您应该使用 multer 内置存储(memoryStorage)方法。

试试下面的代码

const multer = require('multer');
const upload = multer({ storage: multer.memoryStorage() })

app.post('/api/upload', upload.single("file"), (req, res) => {
  console.log(req.file) // it'll return file uploaded from client side
});

推荐阅读