如何使用Express上传和读取文件

时间:2018-09-23 15:23:39

标签: node.js express multer

我有一个问题。我在这里看了一些问题,但是我没有答案。我的问题是,我想上传并读取一个json文件,我尝试使用“ multer”,但不能。所以我想将上传的文件放入结果变量。你能帮助我吗?我该如何实现?

HTML;

<!DOCTYPE html>
<html lang="en">
  <head></head>
  <body>
    <form action="/import" enctype="multipart/form-data" method="post">
      <input type="file" name="filename">
      <input type="submit" value="Upload">
    </form>  
  </body>
</html>

Server.js

const express = require('express');
const multer  = require('multer');
const upload  = multer({
  dest: 'uploads/' // "uploads"
}); 

const app = express();

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

route.post("/import", upload.single("filename") (req, res, next) => {
  var result = require(# I want to send the json file I uploaded here, and I need to see the contents of the json file as is #)
  res.json(result)

      res.redirect("/")
});

app.listen(3000);

1 个答案:

答案 0 :(得分:0)

upload.single()解析数据流,并根据配置将其另存为文件。对于您而言,它将在传入请求中查找filename字段,并将文件保存在uploads/文件夹中。该文件的元数据在req.file对象中可用。您只需执行console.log(req.file)即可查看信息。

要读取文件的内容,可以使用req.file.path字段。方法如下:

const fs = require("fs");
const path = require("path");

/** In the controller */
const absolutePath = path.join(__dirname, req.file.path);
const jsonString = fs.readFileSync(absolutePath, "utf-8");
const jsonObject = JSON.parse(jsonString);
console.log(jsonObject);

完整的server.js如下所示:

const express = require("express");
const multer = require("multer");
const fs = require("fs");
const path = require("path");
const upload = multer({
    dest: "uploads/" // "uploads"
});

const app = express();

app.get("/", (req, res) => {
    res.sendFile(__dirname + "/index.html");
});

const route = express.Router();
route.post("/import", upload.single("filename"), (req, res, next) => {
    console.log(req.file);
    const absolutePath = path.join(__dirname, req.file.path);
    const jsonString = fs.readFileSync(absolutePath, "utf-8");
    const jsonObject = JSON.parse(jsonString);
    console.log(jsonObject);
    res.redirect("/");
});

app.use(route);

app.listen(3000);

我添加了您的代码段中缺少的某些部分(例如express.Router)。但是它们可能有所不同。