【问题标题】:Reading a CSV file in express/multer without saving the file on the server在 express/multer 中读取 CSV 文件而不将文件保存在服务器上
【发布时间】:2021-03-29 08:45:48
【问题描述】:

我目前有一个带有反应前端的快速服务器,我设法使用它从前端发送一个 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>,

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

任何帮助将不胜感激。

【问题讨论】:

  • 保存文件并验证它,如果它没用就删除它
  • 最重要的是,如果它验证了我只想返回一条消息,我根本无法在服务器端存储任何东西,只想直接访问缓冲区对象。
  • @AliElzalmy 你找到解决办法了吗?

标签: node.js reactjs express http multer


【解决方案1】:

你应该使用 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
});

【讨论】:

    【解决方案2】:

    下面的代码对我有用

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-22
      • 2012-09-07
      • 2014-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多