xhr发起请求
<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metahttp-equiv="X-UA-Compatible"content="IE=edge">
<metaname="viewport"content="width=device-width,initial-scale=1.0">
<title>Document</title>
<linkrel="stylesheet"href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css"rel="externalnofollow">
<scriptsrc="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<scriptsrc="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<!--1、文件选择框-->
<inputtype="file"id="file1">
<!--2、上传文件的按钮-->
<buttonid="btnupload">上传文件</button>
<br/>
<divclass="progress"style="width:300px;margin:5px;">
<divclass="progress-barprogress-bar-stripedactive"style="width:0%;"id="precent">
0%
</div>
</div>
<!--3、img标签来显示上传成功以后的图片-->
<imgalt=""id="img"width="800">
<script>
varprecent=document.querySelector('#precent')
varbtnupload=document.querySelector('#btnupload')
btnupload.addEventListener('click',function(){
varfiles=document.querySelector('#file1').files
if(files.length<=0){
returnalert('请选择要上传的文件')
}
varfd=newFormData()
fd.append('avatar',files[0])
varxhr=newXMLHttpRequest()
xhr.upload.onprogress=function(e){
console.log(e);
if(e.lengthComputable){
varh=Math.ceil((e.loaded/e.total)*100)
precent.style.width=h+'%'
precent.innerHTML=h+'%'
console.log(h);
}
}
xhr.upload.onload=function(){
$('#precent').removeClass().addClass('progress-barprogress-bar-success')
}
xhr.open('post','http://www.liulongbin.top:3006/api/upload/avatar')
xhr.send(fd)
xhr.onreadystatechange=function(){
if(xhr.readyState==4&&xhr.status==200){
vardata=JSON.parse(xhr.responseText)
console.log(data);
if(data.status==200){
console.log('上传成功');
document.querySelector('#img').src='http://www.liulongbin.top:3006'+data.url
}else{
console.log('上传失败');
}
}
}
})
</script>
</body>
</html>
ajax发起请求
<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metahttp-equiv="X-UA-Compatible"content="IE=edge">
<metaname="viewport"content="width=device-width,initial-scale=1.0">
<title>Document</title>
<scriptsrc="jquery.js"></script>
<style>
img{
width:50px;
height:50px;
display:none;
}
</style>
</head>
<body>
<inputtype="file"id="file1">
<buttonid="btnupload">上传文件</button>
</br>
<imgsrc="5-121204193R5-50.gif"alt=""id="loading">
<script>
$(function(){
$(document).ajaxStart(function(){
$('#loading').show()
})
$(document).ajaxStop(function(){
$('#loading').hide()
})
$('#btnupload').on('click',function(){
varfiles=$('#file1')[0].files
if(files.length<=0){
alert('请选择文件')
}
console.log('ok');
varfd=newFormData()
fd.append('avatar',files[0])
$.ajax({
method:'POST',
url:'http://www.liulongbin.top:3006/api/upload/avatar',
data:fd,
processData:false,
contentType:false,
success:function(res){
console.log(res);
}
})
})
})
</script>
</body>
</html>
|