Skip to content

Instantly share code, notes, and snippets.

@Bnaya
Created July 20, 2020 08:36
Show Gist options
  • Save Bnaya/131c229de8b906852a473040e75e6f49 to your computer and use it in GitHub Desktop.
Save Bnaya/131c229de8b906852a473040e75e6f49 to your computer and use it in GitHub Desktop.
Basic example of fetch api + expressjs/multer using files and text fields

Basic example of fetch api + expressjs/multer using files and text fields

<html>
<head></head>
<body>
<input type="file" />
<button>Go</button>
<script>
document.querySelector("button").addEventListener("click", async () => {
const formData = new FormData();
formData.append("myFile", document.querySelector("input[type=file]").files[0]);
formData.append("title", "some file title")
formData.append("another-text-field", "another text field value")
const r = await fetch("/dumprequest", {
method: "POST",
body: formData
});
console.log(r.json());
});
</script>
</body>
</html>
{
"name": "express-multer",
"version": "1.0.0",
"main": "index.js",
"author": "Bnaya Peretz",
"license": "MIT",
"dependencies": {
"express": "^4.17.1",
"multer": "^1.4.2",
"start": "node server.js"
}
}
const app = require("express")();
const multerMiddlewareFactory = require("multer");
const path = require("path");
const multerMiddleware = multerMiddlewareFactory();
app.post("/dumprequest", multerMiddleware.fields([{name: "myFile", maxCount: 1}]), (req, res) => {
try {
const file = {...req.files["myFile"][0]}
file.buffer = undefined;
file.size = req.files["myFile"][0].buffer.length;
const dump = {
textFields: req.body,
files: [file]
};
res.send(dump);
} catch (error) {
res.status(500).send(error);
}
});
app.get("/", (req, res) => {
res.sendFile(path.resolve(__dirname, "./index.html"));
});
app.listen(8888, (error) => {
if (error) {
console.error(error);
} else {
console.log("server up");
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment