首页 > 解决方案 > 使用强大/快速时文件不写入磁盘

问题描述

我有一个非常简单的节点脚本,它应该只显示一个带有上传表单的静态网页,并将任何上传的文件写入磁盘。

const formidable = require('formidable')
const http = require('http')
var fs = require('fs');

const app = express()
const serve = http.Server(app)
const PORT = process.env.PORT || '5000'

// Display upload page at root
app.use(express.static('../client'))

//Start HTTP with express
serve.listen(PORT, () => {
    console.log(`Listening on ${PORT}`)
})

app.post('/submit-form', function (req, res){
    var form = new formidable.IncomingForm();

    form.on('fileBegin', function (name, file){
        file.path = __dirname + '/uploads/' + file.name;
    });

    form.parse(req);

    form.on('file', function (name, file){
        console.log('Uploaded ' + file.name);
    });

});

app.listen()

该页面显示得很好,它按预期发送了一个发布请求,但上传后出现此错误:

Error: ENOENT: no such file or directory, open ' the path where the upload should be '
Emitted 'error' event at:
    at lazyFs.open (internal/fs/streams.js:273:12)
    at FSReqWrap.oncomplete (fs.js:141:20)

我找不到任何有类似错误的人,但我假设我可能在做一些愚蠢的事情。

谁能帮我吗?

标签: node.jsexpressformidable

解决方案


在侦听事件之前,您必须先解析请求。尝试这个:

app.post('/submit-form', function (req, res){
    var form = new formidable.IncomingForm();

    form.parse(req)
        .on('fileBegin', function (name, file){
            file.path = __dirname + '/uploads/' + file.name;
        })
        .on('file', function (name, file){
            console.log('Uploaded ' + file.name);
        });
});

推荐阅读