【问题标题】:how to upload and read a file with nodejs / express如何使用 nodejs / express 上传和读取文件
【发布时间】:2014-10-10 07:11:57
【问题描述】:

关于此的各种帖子都有,但我仍然没有得到它。 我想上传 *.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;

【问题讨论】:

  • 您使用哪个中间件与 express 一起处理文件上传? app.js 第 30 行是什么?
  • 您使用 POST 方法发送表单,但声明了 GET 路由。第一步是将您的路线更改为router.post('/import'...,然后重试。
  • 更改了代码...没有骰子。
  • 你在使用bodyparser中间件吗?
  • 我没有使用 bodyparser 中间件。甚至没有意识到它的必要性。会去研究。谢谢。

标签: node.js file-upload express pug


【解决方案1】:

希望这能解决你的问题,这是我的多个上传文件的方法:

节点:

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" 属性。

我希望这可以帮助您;)

【讨论】:

  • Thanx @TirthrajBarot ;) 我只是一个初学者,我会尽力做到最好:P
【解决方案2】:

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

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?
猜你喜欢
  • 2018-01-02
  • 1970-01-01
  • 2018-07-21
  • 2020-08-19
  • 2022-06-14
  • 2023-03-03
  • 2019-03-26
  • 2014-03-16
  • 1970-01-01
相关资源
最近更新 更多