Skip to content

Instantly share code, notes, and snippets.

@WORMSS
Created July 7, 2017 12:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WORMSS/3094fcabebce70f40d2e6bdaa3daacce to your computer and use it in GitHub Desktop.
Save WORMSS/3094fcabebce70f40d2e6bdaa3daacce to your computer and use it in GitHub Desktop.
Example code for uploading a file with express and multer
const express = require("express");
const multer = require("multer");
const upload = multer({"dest": "./mult"});
const app = express();
app.get("/", indexHandler);
app.post("/save", upload.single("fileField"), saveHandler);
app.listen(3000, () => console.log("server started", 3000));
function indexHandler(req, res) {
// enctype="multipart/form-data" is needed for file uploading.
// fileField name matches the upload.single name
var indexContent =
`<form action="/save" method="POST" enctype="multipart/form-data">
<input type="file" name="fileField" />
<button type="submit">Submit</button>
</form>`;
res.status(200).type("html").send(indexContent);
}
function saveHandler(req, res) {
console.log(req.file); // Since it's a single(), it uses .file variable
res.status(200).type("text").send("File: " + JSON.stringify(req.file));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment