Search code examples
node.jsexpressmulter

how to upload and read a file with express


I have question.I've looked at some questions here, but I can't get the answer.My question is, I want to upload and read a json file, I try with "multer" but couldn't.So I want to put the file I upload to the result variable. Can you help me? How can I achieve this?

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

Solution

  • The upload.single() parses the data stream and saves as a file based on the configuration. In your case, it will look for filename field in the incoming request and save the file in the uploads/ folder. The metadata of the file is available in req.file object. You can simply do console.log(req.file) to see the information.

    To read the content of the file, you can use req.file.path field. Here is how:

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

    Here is how the complete server.js would look like:

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

    I have added some parts which were missing from your snippet ( like express.Router ). They might be different though.