简体   繁体   中英

How to retrieve excel .xlsx data from Fastify POST request body?

I am new to noode js and reactjs and I am trying to sending the excel file from react js front end using axios

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",
            },
        });
};

How can I retrieve the excel file on the server side and validate the data in the excel file

Here is my server side code


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;

You have multiple options:

Single file

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

or

Multiple Files

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM