如何使用nodejs / express上传和读取文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25345237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:46:51  来源:igfitidea点击:

how to upload and read a file with nodejs / express

node.jsfile-uploadexpresspug

提问by Simply Seth

there are all kinds of posts about this, but I'm still not getting it. I want to upload a *.csv and read and process its contents.

有各种各样的帖子关于这个,但我仍然没有得到它。我想上传 *.csv 并阅读和处理其内容。

my jade file is this

我的玉文件是这个

//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")

--

——

I changed the code, but req.files is undefined

我更改了代码,但 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;

采纳答案by Simply Seth

The below tutorial gets me super close to where I need to be.

下面的教程让我非常接近我需要去的地方。

NOTE: In the form, it should be:

注意:在表格中,它应该是:

action="/uploads/upload"

I can finally upload and read *.csv files.

我终于可以上传和读取 *.csv 文件了。

http://blog.e-zest.com/how-to-handle-file-upload-with-node-and-express-4-0/

http://blog.e-zest.com/how-to-handle-file-upload-with-node-and-express-4-0/

Here is one of the secret ingredients for reading form data:

这是读取表单数据的秘诀之一:

https://github.com/expressjs/multer

https://github.com/expressjs/multer

I hope this may be of use to someone else who was stuck like me (for 3 days!).

我希望这对像我一样被卡住的其他人有用(3 天!)。

回答by Vino

Convert the uploaded file in to string, using

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

toString('utf8')

toString('utf8')

you can than make any operation on string like convert it to json using csvtojsonpackage

您可以对字符串进行任何操作,例如使用csvtojson包将其转换为 json

Here is the sample code for uploading csv and than convert to 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');
});

working example- csvjsonapi

工作示例 - csvjsonapi

回答by Despertaweb

Hope this solves your question, this is my method to multiple upload file:

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

Nodejs :

节点:

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);
            })
        })
}
})

Make sure your form has enctype="multipart/form-data"

确保您的表单具有 enctype="multipart/form-data"

I hope this gives you a hand ;)

我希望这能帮到你 ;)