express上传和读取文件

express上传和读取文件

本文介绍了如何使用nodejs/express上传和读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我的玉文件是这个

//views/import.jade扩展布局块内容h1=标题表单(动作=/导入",方法=post",enctype=multipart/form-data")输入(类型=文件",名称=ufile")输入(类型=提交",名称=上传")

--

我更改了代码,但 req.files 未定义

//routes/index.js/* 导入页面.*/router.get('/blah', function(req, res, next) {res.render('import', { title: '导入数据' });});router.post('/import', function(req, res) {控制台日志(req.files);});module.exports = 路由器;
解决方案

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

toString('utf8')

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

这里是上传csv然后转换为json的示例代码-

/* csv 到 json */const express = require("express"),app = express(),upload = require("express-fileupload"),csvtojson = require("csvtojson");让 csvData = "测试";app.use(上传());app.get("/", (req, res, next) => {res.sendFile(__dirname + "/index.html");});app.post("/file", (req, res) => {/** 将请求缓冲区转换为 csv 字符串,* "csvfile" 是输入标签中 name 属性给出的文件名 */csvData = req.files.csvfile.data.toString('utf8');返回 csvtojson().fromString(csvData).then(json =>{返回 res.status(201).json({csv:csvData, json:json})})});app.listen(process.env.PORT || 4000, function(){console.log('你的节点js服务器正在运行');});

工作示例 - csvjsonapi

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.

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

//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;
解决方案

Convert the uploaded file in to string, using

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

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

这篇关于如何使用nodejs/express上传和读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 01:52
查看更多