如何解决强大的对象不存储文件?

时间:2018-12-24 16:34:46

标签: node.js express fs formidable

我正在尝试将一个文本文件从表单读入我的node.js应用程序。该文件通过以下形式传递: PS:html代码使用的是pug表示法。

form.md-form(action="/upload", method="POST")
                    .file-field.input-field 
                        button.btn.indigo.waves Browse
                        .file-path-wrapper
                            input.file-path.validate(type = "text", placeholder = "Upload file")
                        input.btn.indigo.waves-light(type="submit")
                        input(type="file", name="document")

但是我得到的只是这个输出:

 Example app listening on port 7000!
 document test_file.txt
 -> upload done
 fields: {"document":"test_file.txt"}
 files: {}

我不明白为什么我的文件向量为空。 预期的输出应该是文本文件的行。

这是我服务器的代码:

const express = require('express');
const app = express();
const port = 7000;
const formidable = require('formidable'); 
const fs = require('fs');

// seting the view engine
app.set('view engine', 'pug');

// serve static files from the `public` folder
app.use(express.static(__dirname + '/public'));

app.get('/', (req, res) => res.render('index',{title: 'Homepage'}));

//uploading a file
app.post('/upload', (req, res) => {
   var form = new formidable.IncomingForm();
   var files = [];
   var fields = [];

   form.keepExtensions = true;
   form.uploadDir = __dirname+'/multipart';

   form
    .on('field', function(field, value) {
        console.log(field, value);
        fields.push([field, value]);
    })
    .on('file', function(field, file) {
        console.log(field, file);
        files.push([field, file]);
    })
    .on('end', function() {
        console.log('-> upload done');
    }
    );
    form.parse(req, (err,fields,files) => {
        console.log('fields: ' + JSON.stringify(fields));
        console.log('files: ' + JSON.stringify(files));
        var document = files.document;
        if (document){
            var name = document.name;
            var path = document.path;
            var type = document.type;
            if (type.indexOf(document) != -1){
            var outputPath = __dirname +'/multipart/' +Date.now() + '_' + name;

                fs.rename(path, outputPath, function(err){
                    res.redirect('/');
                });
            } else {
                fs.unlink(path, (err) => {
                    res.sendStatus(400);
                });
            }
        } else {
            res.sendStatus(404);
        }
    });
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

0 个答案:

没有答案