<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="./lib/jquery.js"></script>
<title></title>
</head>
<body>
<input type="file" id="file1" />
<img src="layui/css/modules/layer/default/loading-0.gif" class="loading" style="display: none;"/>
<img src="layui/css/modules/layer/default/loading-1.gif" class="loading" style="display: none;"/>
<img src="layui/css/modules/layer/default/loading-2.gif" class="loading" style="display: none;" />
<img src="./loading.gif" class="loading" style="display: none;"/>
<button id="sendFile">上传文件</button>
<script>
$(function(){
// 为发送文件按钮绑定单价事件,,判断是否上传了文件
$('#sendFile').on('click',function(){
// 【0】表示转换为原生的dom对象,使用files属性访问文件列表
var files = $('#file1')[0].files
if(files.length <=0 ){
return alert('请选择文件后再上传!')
}
// console.log('ok')
// 使用jQuery发起上传文件请求
var fd = new FormData()
fd.append('avatar',files[0])
$.ajax({
type:'post',
url:'http://www.liulongbin.top:3006/api/upload/avatar',
data:fd,
processData:false,
contentType:false,
success:function(res){
console.log(res)
}
})
})
//点击上传文件后加载图片显示
$(document).ajaxStart(function(){
$('.loading').show()
})
// 文件上传完成后加载图片消失
$(document).ajaxStop(function(){
$('.loading').hide()
})
})
</script>
</body>
</html>
结果
更多推荐
jquery实现文件上传
发布评论