2016-01-13 175 views
1

我想使用文件上傳將CSV文件轉換爲JSON數組對象。使用文件上傳將CSV轉換爲JSON

我已經試過multer,

module.exports = function(express, app, upload){ 
    var router = express.Router(); 
    var util = require('util'); 

    router.get('/',function(req,res){ 
     res.send(200); 
    }); 
    router.post('/csv', upload,function(req,res){ 
     //How to get file contents ? 
     res.send('/dashboard'); 
    }); 
    app.use('/upload',router); 
}; 

其中上傳,

var upload = multer({ storage: storage }).single('csvfile'); 

回答

1

您只需從請求提取體。 bodyparserhttps://github.com/expressjs/body-parser是一個很好的工具。

首先,安裝並需要庫。然後,創建一個text bodyparser(可能爲csv用例最適合),並將其註冊爲一箇中間件:

app.use(bodyParser.json()) // app being 'var app = express()' server 

最後:但是

router.post('/csv', upload,function(req,res){ 
    console.log(req.body) // req.body should be populated by request body 
    res.send('/dashboard'); 
}); 

注意,這bodyparser不適合多身體。如果這是你的情況,請使用https://github.com/felixge/node-formidable

1

Jay。

如果你有小的csv文件,你可以使用內存作爲分割器。

var upload = multer({ inMemory: true}).single('csvfile'); 

並在此之後,你必須將CSV

router.post('/csv', upload, function(req,res){ 
    var csvString = req.files.csvfile.buffer.toString() 
    converter.fromString(csvString, function(err,result){ 
     if(err)return res.send("ERR") 
     res.send(result); 
    }); 
});