当前位置:网站首页>form表单,formdata对象,实现文件上传
form表单,formdata对象,实现文件上传
2022-08-08 06:21:00 【Youser511】
form表单
- action属性:提交表单时,向何处发送表单数据
- target属性:在何处打开url
- _blank 在新窗口打开
- _self 在同一个窗口打开 默认
- _parent
- _top
method属性: 以何种方式把表单数据提交到 action url GET/POST
enctype属性: 发送表单数据之前如何对数据进行编码——主要用于上传图片(post请求)
- application/x-www-form-urlencoded 在发送前编码所有字符(默认)
- multipart/form-data 不对字符编码。在使用包含文件上传控件的表单时,必须使用该值
- text/plain 空格转换为 “+” 加号,但不对特殊字符编码。(很少用)
<form action="/login" method="get">
<input type="text" name="email" id="">
<br/>
<input type="password" name="pass">
<br/>
<input type="submit" value="提交">
</form>
form 只是用来获取数据 ajax发送请求
监听表单的提交事件:
第一种
$('#f1').submit(function(){
alert('监听到表单的提交事件')
})
第二种
$('#f1').on('submit',function(e){
alert('监听到表单的提交事件')
// 阻止默认行为(默认提交)
e.preventDefault()
// 快速获取表单的值(不用再.value了)
var data = $(this).serialize()
console.log(data)
})
FormData对象
为了方便表单处理,HTML5新增了一个FormData对象,可以模拟表单操作
// 1创建FormData对象
var fd = new FormData()
// 2 调用append函数,向fd中追加数据
fd.append('username','zs');
fd.append('pwd',"12345");
var xhr = new XMLHttpRequest()
xhr.open('POST','http://www.liulongbin.top:3006/api/formdata');
xhr.send(fd)
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status ===200){
console.log(JSON.parse(xhr.responseText))
}
}
==>
<form id="form1">
<input type="text" name="username" autocomplete="off">
<br/>
<input type="password" name="pwd" >
<br/>
<button type="submit">提交</button>
</form>
// 1 dom操作获取form表单元素
var form = document.querySelector("#form1");
form.addEventListener('submit',function(e){
// 阻止表单的默认行为
e.preventDefault();
// 创建FormData 快速获取到form表单中的数据
var fd = new FormData(form);
var xhr = new XMLHttpRequest()
xhr.open('POST','http://www.liulongbin.top:3006/api/formdata');
xhr.send(fd)
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status ===200){
console.log(JSON.parse(xhr.responseText))
}
}
})
主要还是用来上传文件
上传文件
XMLHttpRequest对象,不仅可以发送文本信息,还可以上传文件
1:定义ui结构
2:验证是否选择了文件
3:向FormData中追加文件
4:使用xhr发起上传文件的请求
5:监听onreadystatechange事件
<!-- 1文本选择器 -->
<input type="file" id="file1">
<!-- 2上传文件按钮 -->
<button id="btnUpload">上传文件</button>
<hr/>
<!-- img显示上传成功后的图片 -->
<img src="" id="img" alt="">
// 1获取文件上传按钮
var btn = document.querySelector("#btnUpload");
// 绑定事件
btn.addEventListener('click',function(){
// 3获取用户选择的文件列表
var files = document.querySelector("#file1").files;
console.log(files,0)
// 验证是否选择了文件
if(files.length <= 0){
return alert("请选择要上传的文件");
}
var fd = new FormData();
// 将用户选择的文件添加到FormData中
fd.append('avatar',files[0]);
var xhr = new XMLHttpRequest()
xhr.open('POST','http://www.liulongbin.top:3006/api/upload/avatar');
xhr.send(fd)
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status ===200){
// console.log(JSON.parse(xhr.responseText))
var data = JSON.parse(xhr.responseText);
if(data.status===200){
document.querySelector('#img').src ='http://www.liulongbin.top:3006' + data.url
}else{
alert("图片上传失败")
}
}
}
})
显示文件上传进度
XMLHttpRequest对象可以通过监听xhr.upload.onprogress事件,来获取文件的上传进度
引入bootstrap,并加进度条显示
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<!-- bootstrap进度条 -->
<div class="progress" style="width: 500px; margin: 15px 10px;">
<div class="progress-bar progress-bar-striped active" id="percent" style="width: 0%;">
0%
</div>
</div>
<!-- img显示上传成功后的图片 -->
<img src="" id="img" alt="">
在创建XML对象之后
var xhr = new XMLHttpRequest();
// 监听文件上传的进度
xhr.upload.onprogress = function(e){
// console.log(1)
if(e.lengthComputable){
// 计算上传的进度 计算当前上传进度的百分比
var procentComplete = Math.ceil((e.loaded / e.total)*100);
// console.log(procentComplete)
// 动态设置进度条
$("#percent").attr('style','width:' + procentComplete + '%;').html(procentComplete + '%')
}
}
// 监听上传完成的事件
xhr.upload.onload = function(){
$("#percent").removeClass().addClass('progress-bar progress-bar-success')
}
使用jQuery实现文件上传
1定义ui结构
<input type="file" id="file1">
<button id="btn">上传文件</button>
<br/>
<img src="./loading.gif" style="display: none;" id="loading" alt="">
2验证是否选择了文件
var files = $("#file1")[0].files;
if(files.length <= 0){
return alert("请选择文件后再上传");
}
3:向FormData中追加文件
// 追加到formdata中
var fd= new FormData();
fd.append('avatar',files[0])
4:使用jquery发起上传文件得请求
// 发起jquery得ajax请求 上传文件
$.ajax({
method:'POST',
url:"http://www.liulongbin.top:3006/api/upload/avatar",
data:fd,
// 不修改Content-Type属性 使用FormData默认的Content-Type
contentType:false,
// 不对FormData中的数据进行url编码 而是将FormData数据原样发送到服务器
processData:false,
success:function(res){
console.log(res)
}
})
5jQuery实现loading效果
1:ajaxStart(callback)
ajax请求开始时,执行ajaxStart,可以在它的callback中显示loading效果
// 监听ajax请求被发起了 会监听当前页面中所有的ajax请求
$(document).ajaxStart(function(){
$("#loading").show()
})
2:ajaxStop(callback)
ajax请求结束时,执行ajaxStop函数,可以在callback中隐藏loading效果
$(document).ajaxStop(function(){
$("#loading").hide()
})
边栏推荐
- Completed - desktop interactive wizard design based on facial expressions (share the results, attach the data set of facial expressions and the yolov5 model trained by yourself and the interactive int
- 4G/5G频谱资源协同关键技术
- 【ESP8266】ESP12S/12F 最小系统设计及typeC自动下载电路设计
- 从ELF格式分析arm动态链接原理
- 网络安全:系统文件属性
- C语言中求两数最大公约数的三种方法
- BAT必问JVM,你了解吗?
- 2021年度总结
- MySQL数据库
- 2021 mathematical modeling national competition question B
猜你喜欢

“忙碌”的 Polkadot最新努力,对DOT投资者意味着什么?

整数分块例题

BAT必问JVM,你了解吗?

How many times the neural network is generally trained, the neural network training time is too long

Sentinel流控规则绑定nacos持久化

PostgreSQL中想新建一个用户,让他仅能访问指定数据表,不能通过客户端工具看到表结构和函数内容,是否有方案可解决?

使用XGboost进行分类,判断该患者是否患有糖尿病

stack-queue

YoloV4训练自己的数据集(四)

Docker安装nacos2.0并指定mysql,安装sentinel
随机推荐
Synchronization and Asynchrony of Clocks
YoloV4训练自己的数据集(三)
State Compression Review
遥远的救世主
为什么有些参数reload就可以生效,而有些参数必须重启数据库?
字符串哈希 哈希值
ValueError: Length of feature_names, 4 does not match number of features, 2 的解决方法
string hash hash value
vim 快捷键大全和插件大全
信息传输率(Information Translate Rate,ITR)
YoloV4训练自己的数据集(四)
LLVM系列第二十九章:写一个简单的常量加法“消除”工具(Pass)
redis客户端Jedis/Redisson/Letture对比示例代码
Runtime - KVC, KVO principle
刚学,这是怎么回事,SQL怎么转运错误啊
不知道取什么名字
The pta patching simple graph theory
stack-queue
打开deploy和manager图形化界面打不开
Rust学习:3_变量绑定与解构