Created
January 13, 2025 05:12
-
-
Save Tribhuwan-Joshi/e3157e8e45ee86991cc53748268ee776 to your computer and use it in GitHub Desktop.
Native handling of file upload in NodeJs - no library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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