Skip to content

Instantly share code, notes, and snippets.

@Tribhuwan-Joshi
Created January 13, 2025 05:12
Show Gist options
  • Save Tribhuwan-Joshi/e3157e8e45ee86991cc53748268ee776 to your computer and use it in GitHub Desktop.
Save Tribhuwan-Joshi/e3157e8e45ee86991cc53748268ee776 to your computer and use it in GitHub Desktop.
Native handling of file upload in NodeJs - no library
const inputButton = document.getElementById("inputtag");
const buttonn = document.querySelector(".btn");
inputButton.addEventListener("change", async (e) => await updateFile(e));
buttonn.addEventListener("click", () => uploadFile());
let data = null;
async function updateFile(e) {
const file = e.target.files[0];
const formData = new FormData();
formData.append("image", file);
data= formData;
}
async function uploadFile() {
try {
const imageData = await fetch("http://localhost:5000/upload", {
method: "POST",
headers: {
"Content-Type": "multipart/form-data",
},
body: data,
});
} catch (err) {
console.log(err);
}
}
app.post("/upload", async (req, res) => {
let data = [];
req.on("data", (chunk) => {
data.push(chunk);
});
req.on("end", () => {
let fileData = Buffer.concat(data);
fs.writeFile(
path.join(__dirname, "example.pdf"),
fileData,
"base64",
(err) => {
if (err) {
res.statusCode = 500;
}
}
);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment