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

时间:2019-04-02 12:15:40

标签: node.js express multer

我要保存用户上传的文件。之前我为此使用Option Explicit Private Sub Worksheet_Change(ByVal Target As Range) Dim LastRow As Long Dim WsSource As Worksheet, WsDest As Worksheet Set WsSource = ThisWorkbook.Sheets("Sheet1") Set WsDest = ThisWorkbook.Sheets("Sheet2") If Intersect(Target, WsSource.Range("I:I")) Is Nothing Then Exit Sub End If Application.EnableEvents = False On Error GoTo ErrHandler Debug.Print LastRow With WsDest LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1 Debug.Print LastRow If UCase(Target.Text) = "YES" Then .Range("A" & LastRow).Resize(, 50).Value = _ WsSource.Range("A" & Target.Row).Resize(, 50).Value Debug.Print "Record added" End If End With ExitHere: Application.EnableEvents = True Exit Sub ErrHandler: Resume ExitHere End Sub ,但是我想运行一些验证,因此在这种情况下,我的multer无法正常工作。如果验证通过,我想在这里使用multer保存输出,但是我的数据作为缓冲区传来,我不知道如何保存。

fs.write

excelMiddleware.js

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

1 个答案:

答案 0 :(得分: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>')
    })
})