FormData上传进程监听

37 篇文章 0 订阅
6 篇文章 1 订阅

效果图

在这里插入图片描述

FromDtata.html

<style>
.info {
  width: 500px;
  min-height: 200px;
  border: 1px solid red;
  margin: 0 auto;
}

.out {
  width: 80%;
  height: 20px;
  margin: 50px auto;
  border: 1px solid red;
  overflow: hidden;
}

.in {
  height: 100%;
  width: 5%;
  background-color: blue;
}
</style>
<form>
  用户名:
  <input type="text" name="username">
  密码:
  <input type="password" name="password">
  头像:
  <input type="file" name="photo">
  <!-- 
   submit 按钮 默认行为是提交表单, 页面会刷新的 , 看不到ajax前请求的效果 
   在配合ajax使用时, 阻止按钮的默认行为  return false;  e.preventDefault(); 
  -->
  <input type="submit" class="btn" value="提交">
</form>
<!-- 进度条 -->
<div class="out">
 <div class="in"></div>
</div>
<h1></h1>
<script>
// 点击按钮,获取表单的数据和图片 传递给后台 , 显示文件上传进度 ,显示在进度条中 
 document.querySelector('.btn').onclick = function (e) {
     e.preventDefault(); //  阻止按钮的默认行为 
     // 获取表单的数据和图片 传递给后台
     var fd = new FormData(document.querySelector('form'));
     // 传递给后台 ajax  
     var xhr = new XMLHttpRequest();
     // 请求报文
     xhr.open('post', './03-progress.php');

     // 监听文件上传进度 
     xhr.upload.onprogress = function (e) {
       // 获取进度 = 已经上传大小/文件总大小 
       // e.total 文件总大小 
       // e.loaded 已经上传的大小 
       var value = e.loaded / e.total;
       console.log(parseInt(value * 100) + '%');
       // 让进度条同步
       document.querySelector('.in').style.width = parseInt(value * 100) + '%';
       document.querySelector('h1').innerText = parseInt(value * 100) + '%';
     }

     xhr.send(fd);

     //监听响应
     xhr.onload = function () {
       console.log(xhr.responseText);
     }
 }
</script>

FromDtata.php

<?php 
  echo 'formData';
?>

FromDtata.css

*{
    margin: 0;
    padding: 0;
}

body{
    background:#ccc;
}

h1,h2,h3,h4,h5,h6{
    text-align: center;
}

form{
    width: 400px;
    margin:50px auto;
    padding:20px;
    border: 1px solid #eee;
    border-radius: 10px;
    background:#fff;
}

input[type='text'],
input[type='select'],
input[type='password'],
input[type='submit'],
input[type='password'],
input[type='button'],
input[type='file'],
select{
    width: 100%;
    display: block;
    height: 24px;
    margin-bottom:15px;
    border-radius: 3px;
    border:1px solid #aaa;
}

input[type='submit']{
    height: 40px;
    background:rgb(209, 92, 92);
    border:none;
    color:#fff;
    font-size: 24px;;

}


input[type='radio'],
input[type='checkbox']{
    height: 20px;
    width:20px;    
    /* display: inline; */
    margin:10px;
}

input[type='file']{  
    border:none;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值