【问题标题】:How to retrieve excel .xlsx data from Fastify POST request body?如何从 Fastify POST 请求正文中检索 excel .xlsx 数据?
【发布时间】:2021-07-21 02:09:46
【问题描述】:

我是 noode js 和 reactjs 的新手,我正在尝试使用 axios 从 react js 前端发送 excel 文件

import axios from 'axios';

export const uploadFile = async (file) => {

    let formData = new FormData();
    formData.append("file", file);

    return await axios.post("/uploadFile", formData, {
            headers: {
                'Content-Type': 'multipart/form-data',
                accept: "application/json",
            },
        });
};

如何在服务器端检索excel文件并验证excel文件中的数据

这是我的服务器端代码


async function uploadFile(fastify) {

    fastify.register(require('fastify-multipart'));
    fastify.post('/uploadFile', async (req, res) => {

    // How to retrieve the excel file from the request body???
      
    });
}

module.exports = uploadFile;

【问题讨论】:

    标签: node.js reactjs excel fastify


    【解决方案1】:

    您有多种选择:

    单个文件

    const fs = require('fs')
    const pump = require('pump')
    const Fastify = require('fastify')
    const fastifyMultipart = require('fastify-multipart')
    
    const fastify = Fastify({ logger: true })
    
    fastify.register(fastifyMultipart)
    
    fastify.post('/', async function (req, reply) {
      // return the first file submitted, regardless the field name
      const data = await req.file()
    
      // we must consume the file
      // we use pump to manage correctly the stream and wait till the end of the pipe
      // without using `pump` it would be necessary to manage the stream by ourself
      const storedFile = fs.createWriteStream('./img-uploaded.png')
      await pump(data.file, storedFile)
    
      return { upload: 'completed' }
    })
    

    多个文件

    fastify.post('/multiple', async function (req, reply) {
      // get all the files in the request payload
      // `const files` is an async generator
      const files = await req.files()
    
      for await (const part of files) { // iterate the async generator
        req.log.info('storing %s', part.filename)
        const storedFile = fs.createWriteStream(`./${part.filename}`)
        await pump(part.file, storedFile)
      }
    
      return { upload: 'completed' }
    })
    

    【讨论】:

      猜你喜欢
      • 2021-02-08
      • 2019-07-15
      • 1970-01-01
      • 2022-10-06
      • 1970-01-01
      • 2020-01-09
      • 1970-01-01
      • 1970-01-01
      • 2014-05-18
      相关资源
      最近更新 更多