Как я могу поместить файл в локальный каталог и работать с ним без перезагрузки?
Я пробовал разные способы отправки запроса клиенту и серверу, пробовал синхронно записывать файл в каталог, ничего не помогает.
У меня есть такой код моей формы в html:
Код: Выделить всё
Check file
Код: Выделить всё
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);
}
});
Код: Выделить всё
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")
});
});
Подробнее здесь: https://stackoverflow.com/questions/793 ... tefilesync
Мобильная версия