如何在nodejs中保存通过api上传的文件

问题描述 投票:1回答:1

我想保存用户上传的文件。早些时候我正在使用multer,但我想运行一些验证,所以在这种情况下我的multer不起作用。在这里我想使用fs.write来保存输出,如果验证通过,但我的数据作为缓冲区而来,我不知道如何保存它。

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;
node.js express multer
1个回答
0
投票

假设您正在写入服务器上的文件。为此您需要fs.writeFile()文档: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>')
    })
})

© www.soinside.com 2019 - 2024. All rights reserved.