我家空空 2022-08-28 20:47 采纳率: 50%
浏览 89
已结题

ajax上传文件后,页面为什么会刷新?

使用ajax向后端发送文件,为什么上传成功后,页面会刷新呢?
先看下效果:

img

前端代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  
</head>
<body>
  <input type="file" id="upload">
  <input class="upload-btn" type="button" value="点击上传" />
  <script>
    window.onload = function () {
      alert('页面刷新了');
    }
    const btn = document.querySelector('.upload-btn');
    btn.addEventListener('click', function (e) {
      let xhr;
      if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
      } else {
        // 兼容IE
        xhr = ActiveXObject('Microsoft.XMLHTTP');
      }
      let fd = new FormData();
      const file = document.querySelector('#upload');
      console.log(file.files);
      fd.append('file', file.files[0]);
      // 初始化
      console.log('UNSEDN', xhr.readyState);
      // 打开连接
      xhr.open('post', 'http://localhost:3001/upload');
      // xhr.setRequestHeader('Content-Type', 'multipart/form-data');
      xhr.send(fd);
      xhr.onreadystatechange = function () {
        if(this.readyState === 2){
       // 接收到响应头
        console.log("HEADERS_RECEIVED",xhr.readyState);
        }else if(this.readyState === 3){
            // 响应体加载中
          console.log("LOADING",xhr.readyState);
        }else if(this.readyState === 4){
            // 加载完成
            alert('加载完成了');
            console.log("DONE",xhr.readyState);
        }
      }
      // return false;
    });
  </script>
</body>
</html>

后端代码:

const http = require('http');
const querystring = require("querystring");
const fs = require('fs');
const server = http.createServer((req, res) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  if (req.url === '/') {
    req.on('data', (data) => {
      console.log(data.toString());
    })
    req.on('end', () => {
      res.end('124');
    })
  }
  if (req.url === '/upload') {
    if (req.method.toLowerCase() === 'get') {
      // 返回一个用于文件上传的form
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.end(
        `
        <form action="upload" enctype="multipart/form-data" method="POST">
          <input type="file" name="upload" multiple="multiple" />
          <input type="submit" value="Upload" />
  </form>
        `
      )
    } else if (req.method.toLowerCase() === 'post') {
      if (req.headers['content-type'].indexOf('multipart/form-data') !== -1) {
        parseFormData(req, res);
      } else {
        res.end('你好')
      }
    }
  }
});

function parseFormData (req, res) {
  req.setEncoding('binary');
  let body = '';  // 文件数据
  let fileName = ''; // 文件名

  // 边界字符串
  const boundary = req.headers['content-type']
                      .split('; ')[1]
                      .replace('boundary=', '');
  req.on('data', function (chunk) {
    body += chunk;
  });

  req.on("end", function() {
    const file = querystring.parse(body, "\r\n", ":");
    const fileInfo = file["Content-Disposition"].split(";");
    for (value in fileInfo) {
      if (fileInfo[value].indexOf("filename=") !== -1) {
        fileName = fileInfo[value].substring(11, fileInfo[value].length - 1);
        // 这是处理什么情况的?
        if (fileName.indexOf("\\") != -1) {
          fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
        }
        break
      }
    }

    const entireData = body.toString();
    contentType = file["Content-Type"].substring(1);
    //获取文件二进制数据开始位置,即contentType的结尾
    const upperBoundary = entireData.indexOf(contentType) + contentType.length;
    const shorterData = entireData.substring(upperBoundary);
    // 替换开始位置的空格
    const binaryDataAlmost = shorterData
        .replace(/^\s\s*/, "")
        .replace(/\s\s*$/, "");
    // 去除数据末尾的额外数据,即: "--"+ boundary + "--"
    const binaryData = binaryDataAlmost.substring(0, binaryDataAlmost.indexOf("--" + boundary + "--"));
    const bufferData = new Buffer.from(binaryData, "binary");

    fs.writeFile(fileName, bufferData, function(err) {
      if (err) {
        console.log(err);
      }
      res.end("sucess");
    });
});
}

server.listen(3001);
  • 写回答

1条回答 默认 最新

  • Z_pigeon 2022-08-28 21:21
    关注

    看到你这里是动态添加了个form标签的,原生form表单提交的话就会有这个问题,可以看下这个链接,或者根据这个链接的标题搜索更多答案
    https://blog.csdn.net/weixin_47896488/article/details/122511889

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 10月11日
  • 已采纳回答 10月3日
  • 创建了问题 8月28日

悬赏问题

  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知