Skip to content

Instantly share code, notes, and snippets.

@AsaoluElijah
Created June 28, 2021 00:55
Show Gist options
  • Save AsaoluElijah/081fac32abf29d20bb93d8fa72e052a5 to your computer and use it in GitHub Desktop.
Save AsaoluElijah/081fac32abf29d20bb93d8fa72e052a5 to your computer and use it in GitHub Desktop.
Upload and read uploaded file content in express.js
/*
⚠ First install express and multer by running:
npm i -s express multer
*/
const express = require("express");
const multer = require("multer");
const path = require('path')
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
const app = express();
// Index route
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, '/index.html'));
});
app.post("/convert", upload.single("myFile"), (req, res) => {
let file = req.file;
// File content here 👇
const fileContent = Buffer.from(file.buffer).toString("utf-8");
res.send(fileContent);
});
app.listen("5050");
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<form action="/convert" enctype="multipart/form-data" method="POST">
<input type="file" name="myFile" id="" />
<br />
<button type="submit">Continue</button>
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment