Reputation: 1
I can't prevent reloading page when i uncomment string fs.writeFile function. When i haven't this function in my code, browser keeps it's state and doesn't reload the page. How can i put my file in local directory and work with it without reloading?
I tried different ways of sending request to client and server, tried to write file in directory synchronously and nothing helps. I have such code of my form in html:
<form id="metadata-form">
<input type="file" id="file-input" required/>
<button id="process-file-button" type="button">Check file</button>
</form>
There is my client code:
document.getElementById("process-file-button").addEventListener("click", async (event) => {
event.preventDefault();
const formData = new FormData();
const fileInput = document.getElementById("file-input");
if (!fileInput.files.length) {
alert("Выберите файл для загрузки!");
return;
}
formData.append("file", fileInput.files[0]);
try {
const response = await fetch("http://localhost:3000/process-file", {
method: "POST",
body: formData,
});
if (!response.ok) {
throw new Error("Error sending to server");
}
const result = await response.json();
console.log(result)
} catch (error) {
console.error("Error:", error);
}
});
And part of server:
app.post("/process-file", async (req, res) => {
if (!req.files || !req.files.file) {
return res.status(400).json({
error: "Файл не загружен"
});
}
const uploadedFile = req.files.file;
const tempFilePath = path.join(__dirname, "uploads", uploadedFile.name);
fs.writeFile(tempFilePath, uploadedFile.data, (err) => {
if (err) {
console.error("Ошибка при сохранении файла:", err);
return res.status(500).json({
error: "Ошибка сохранения файла"
});
}
console.log("Файл успешно сохранен:", tempFilePath);
res.json("Success")
});
});
How can i put my file in local directory and work with it without reloading?
Upvotes: -1
Views: 46