I am learning how to handle files with multer, to do this i wrote a simple code that takes the uploaded file, parse it to an api that retrieves the the data from the text file and returns the said data, after that i simple modify the paragraph’s text content to be this data from the file.
The problem is that text content flashes for a moment and then the page returns to its prior form. I reckon the web page refreshes after the form submission despite me adding preventDefault();
Please help me understand what i did wrong.
I am a beginner so go easy on me if i made a silly mistake.
I am attaching coding from all the files below:
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FILE HANDLING</title>
</head>
<body>
<h1>Upload a file below</h1>
<!-- action="http://localhost:3000/upload" -->
<form method="post" enctype="multipart/form-data" id="FileSubmitForm">
<label for="FileInput">Upload a file: </label>
<input type="file" id="FileInput" name="file" required>
<button type="submit">Upload</button>
</form>
<p id="displayContent">To be changed</p>
<script src="file.js"></script>
</body>
</html>
file.js:
document.getElementById("FileSubmitForm").addEventListener("submit", (event)=>{
event.preventDefault();
console.log("form submission prevented");
// event.stopPropagation();
const fileInput = document.getElementById("FileInput");
const formData = new FormData();
formData.append("file", fileInput.files[0]);
fetch('http://localhost:3000/upload', {
method: 'POST',
body: formData
})
.then((response)=>response.json())
.then((data)=>{
console.log("success, server response:");
console.log(data)
console.log("This is what we are changing the content with");
let newText = data.result;
console.log(newText);
document.getElementById('displayContent').textContent = newText;
// document.getElementById('displayContent').style.display = 'block';
})
.catch((err)=>{
console.error("Error", err);
});
});
apifile.js:
const express = require('express');
const cors = require('cors');
const fs = require('fs');
const multer = require('multer');
const app = express();
app.use(cors());
// if(!fs.existsSync('./uploads')){
// fs.mkdir('./uploads');
// }
const upload = multer({ dest: 'uploads/' }); // Configure multer to store files in the 'uploads' directory
app.post('/upload', upload.single('file'), (req, res) => {
const file = req.file;
console.log(req.file);
if (!file) {
return res.status(400).json({ result: 'No file uploaded' });
}
// Read the file contents
fs.readFile(file.path, 'utf8', (err, data) => {
if (err) {
console.error(err);
return res.status(500).json({ result: 'Error reading file' });
}
res.status(200).json({ result: data });
});
});
app.listen(3000, () => {
console.log('API is running on http://localhost:3000');
});
I tried using preventDefault() but it doesn’t work