You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用multer处理文件时段落内容闪过后消失的问题求助

问题:Multer文件上传后页面自动刷新,preventDefault()无效

我正在学习使用Multer处理文件上传,编写了一套流程:上传文件后通过API读取文本文件内容并返回,再将页面段落的textContent修改为返回的数据。但目前遇到问题:段落内容闪过后页面就恢复原状,明明已经添加preventDefault(),页面依然会刷新,请求帮忙排查错误。

以下是所有文件代码:

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');
});

排查与解决方案

1. 确保事件监听器正确绑定

脚本虽放在HTML底部,但仍可能因DOM未完全加载导致事件监听器绑定失败,preventDefault()自然无效。可将代码包裹在DOMContentLoaded事件中,确保DOM加载完成后再绑定:

document.addEventListener('DOMContentLoaded', () => {
  document.getElementById("FileSubmitForm").addEventListener("submit", (event)=>{
    event.preventDefault();
    // 后续原有代码保持不变
  });
});

2. 添加双重保险阻止默认行为

在事件处理函数末尾加上return false;,作为preventDefault()的补充,避免浏览器默认行为触发:

document.getElementById("FileSubmitForm").addEventListener("submit", (event)=>{
  event.preventDefault();
  // 原有业务代码...
  return false;
});

3. 检查控制台错误

打开浏览器开发者工具(F12)的控制台面板,查看是否有报错信息。比如CORS配置异常、文件读取失败、fetch请求报错等,这些错误可能导致代码执行中断,间接引发页面异常刷新。

4. 修复服务器端文件夹创建逻辑

服务器代码中创建uploads文件夹的代码被注释了,建议打开并改用同步创建方法,避免因文件夹不存在导致Multer上传失败:

if(!fs.existsSync('./uploads')){
    fs.mkdirSync('./uploads');
}

5. 检查是否有重复事件绑定

在控制台执行getEventListeners(document.getElementById('FileSubmitForm')),查看submit事件的绑定数量。如果存在多个绑定,可能有其他代码覆盖或干扰了你的阻止逻辑。


内容的提问来源于stack exchange,提问作者Abhinav Tanwar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 21:13:16