如何使用Node.js/Express上传和读取文件

27

关于这个问题有各种各样的帖子,但我还是不太明白。我想上传一个*.csv文件并读取和处理其中的内容。

我的jade文件是这个

//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;

你在使用Express处理文件上传时使用哪个中间件?app.js的第30行是什么? - Volune
你正在使用POST方法发送表单,但却声明了一个GET路由。第一步是将你的路由改为router.post('/import'...,然后再试一遍。 - ffflabs
修改了代码...没有成功。 - Simply Seth
你是否正在使用bodyparser中间件? - John Teague
我没有使用bodyparser中间件。甚至不知道它的必要性。我会去研究一下。谢谢。 - Simply Seth
2个回答

16

将上传的文件转换为字符串,使用

 

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


这正是我想做的事情,但出于某种原因它对我不起作用。缓冲对象上的toString()方法只返回空值。我尝试了您的工作示例,并且使用相同的文件运行良好,所以我真的不知道为什么它会在这里工作而不是在我的代码中,我正在访问req.files.[name].data并且它返回缓冲区,添加toString()方法不返回预期的字符串。是否有一种方法可以直接将原始数据提供给csvtojson? - xunux

5
希望这能解决你的问题,以下是我用于多文件上传的方法:
Node.js:
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"属性。

希望这能对您有所帮助 ;)


谢谢@TirthrajBarot ;) 我只是一个初学者,我会尽力的 :P - Despertaweb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接