Sim*_*eth 16 file-upload node.js express pug
有关于此的各种帖子,但我仍然没有得到它.我想上传*.csv并阅读并处理其内容.
我的玉文件就是这个
//views/import.jade
extends layout
block content
h1= title
form(action="/import", method="post", enctype="multipart/form-data")
    input(type="file", name="ufile")
    input(type="submit", name="Upload")
-
我更改了代码,但req.files未定义
//routes/index.js
/* import page. */
router.get('/blah', function(req, res, next) {
  res.render('import', { title: 'Import Data' });
});
router.post('/import', function(req, res) {
    console.log(req.files);
});
module.exports = router;
Vin*_*ino 13
将上传的文件转换为字符串,使用
toString('utf8')
您可以对字符串进行任何操作,例如使用csvtojson包将其转换为 json
这是上传csv然后转换为json的示例代码-
/* csv to json */
const express = require("express"),
  app = express(),
  upload = require("express-fileupload"),
  csvtojson = require("csvtojson");
let csvData = "test";
app.use(upload());
app.get("/", (req, res, next) => {
  res.sendFile(__dirname + "/index.html");
});
app.post("/file", (req, res) => {
/** convert req buffer into csv string , 
*   "csvfile" is the name of my file given at name attribute in input tag */
  csvData = req.files.csvfile.data.toString('utf8');
  return csvtojson().fromString(csvData).then(json => 
    {return res.status(201).json({csv:csvData, json:json})})
});
app.listen(process.env.PORT || 4000, function(){
  console.log('Your node js server is running');
});
工作示例 - csvjsonapi
以下教程让我非常接近我需要的位置.
注意:在表单中,它应该是:
action="/uploads/upload"
我终于可以上传和阅读*.csv文件了.
http://blog.e-zest.com/how-to-handle-file-upload-with-node-and-express-4-0/
这是阅读表单数据的秘诀之一:
https://github.com/expressjs/multer
我希望这可能对像我这样被困的其他人有用(3天!).
希望这能解决您的问题,这是我的多个上传文件的方法:
节点:
router.post('/upload', function(req , res) {
    var multiparty = require('multiparty');
    var form = new multiparty.Form();
    var fs = require('fs');
    
    form.parse(req, function(err, fields, files) {  
        var imgArray = files.imatges;
    
    
        for (var i = 0; i < imgArray.length; i++) {
            var newPath = './public/uploads/'+fields.imgName+'/';
            var singleImg = imgArray[i];
            newPath+= singleImg.originalFilename;
            readAndWriteFile(singleImg, newPath);           
        }
        res.send("File uploaded to: " + newPath);
    
    });
    
    function readAndWriteFile(singleImg, newPath) {
    
            fs.readFile(singleImg.path , function(err,data) {
                fs.writeFile(newPath,data, function(err) {
                    if (err) console.log('ERRRRRR!! :'+err);
                    console.log('Fitxer: '+singleImg.originalFilename +' - '+ newPath);
                })
            })
    }
})
确保您的表单标签具有enctype="multipart/form-data"属性。
我希望这可以帮助你;)