gpt4 book ai didi

node.js - 如何在nodejs中保存通过api上传的文件

转载 作者:太空宇宙 更新时间:2023-11-04 01:32:57 24 4
gpt4 key购买 nike

我想保存用户上传的文件。早些时候,我使用 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;

最佳答案

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

关于node.js - 如何在nodejs中保存通过api上传的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55474572/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com