简体   繁体   中英

how to save files uploaded through api in nodejs

I want to save the uploaded file by the user. Earlier I was using the multer for that but I want to run some validation so in this case my multer is not working. Here I want to use the fs.write to save the output if the validation pass but my data is coming as buffer I don't know how to save it.

const express = require('express');
const app = express();
const multer = require('multer');
const fs = require('fs');

const router = express.Router();
const uploadExcel = require('./excelMiddleware');

const multerS = multer();
router.post('/upload', multer.single('file'), uploadExcel, (req, res) => {
    fs.write('/path/to/file') // want to write here
  res.send('<h1>file uploaded</h1>')
})

router.get('*', (req, res) => {
  res.send('<h1>Page not found</h1>')
})

app.use(router);

app.listen(8000, ()=> {
  console.log('Server stared')
})

excelMiddleware.js

const XLSX = require('xlsx');
const { CONTACT } = require('./column.config');
const _ = require('lodash');

const uploadExcel = (req, res, next) => {
    try{
      const columnMapper = CONTACT;
      const workbook = XLSX.read(req.file.buffer, {type:'buffer'});
      const sheetName = workbook.SheetNames;
      const excelJson = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName[0]]);
      if(!excelJson.length) {
          throw Error("Blank sheet");
      }
      const columnCheck = Object.keys(excelJson[0]);
      const isColumnEqual = _.isEqual(columnMapper, columnCheck);
      if(!isColumnEqual){
        throw Error("Blank sheet");
      }

      next();
    }
    catch(e){
      console.log(e)
      return res.status(400).send({error:e.message});
    }
}


module.exports = uploadExcel;

Assuming that you are writing to a file on the server. For that you want fs.writeFile() Documentation: fs.writeFile()

router.post('/upload', multer.single('file'), uploadExcel, (req, res) => {
    // req.file.file is the uploaded file in memory   
    fs.writeFile('/path/to/file', req.file.file.buffer, (err) => {
        if (err) {
            console.log('do something with err', err)
            // throw error maybe
        }
        // file was uploaded successfully
        res.send('<h1>file uploaded</h1>')
    })
})

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