首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从Fastify请求体中检索excel .xlsx数据?

如何从Fastify请求体中检索excel .xlsx数据?
EN

Stack Overflow用户
提问于 2021-04-28 01:37:06
回答 1查看 258关注 0票数 1

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

代码语言:javascript
复制
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文件中的数据?

下面是我的服务器端代码

代码语言:javascript
复制
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;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-28 12:50:17

您有多个选项:

单列

代码语言:javascript
复制
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' }
})

多个文件

代码语言:javascript
复制
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' }
})
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67288035

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档