js无刷新异步上传文件

小菜鸟战斗机 2018-3-26 188

最近写了个无刷新异步上传文件的js小函数,供参考,有不足之处请多指教。
之前网上找的都是要插件的,我最后自己写了个不需要插件了,封装成函数的代码。
html代码:
[code]<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>点击图片上传(单文件,可封装)</title>
</head>
<style>

up_id{ overflow:hidden;display:block;width:100px; height:100px;}

f_a{display:block;width:100px; height:100px;background:url(1.jpg) no-repeat center; overflow:display; background-size:cover; transition:all 2s;}

f_a input{display:block;width:100px; height:100px;opacity:0; cursor:pointer;}

f_a:hover{ -webkit-transform-origin:center; -webkit-transform:scale(1.5,1.5);}

</style>
<body>
<div id="up_id">
<a id="f_a">
<input type="file" name="file" id="imageFile" multiple>
</a>
</div>
<button id="upload" >点击图片上传</button>
</body>
<script>
(function(){
var upload=document.getElementById('upload');
//var img=document.getElementById('imageFile');

var myurl = "http://192.168.235.5:8089/php/upload/upload1.php";
upload.addEventListener('click',function(){
    ajaxFileUpload({
        url:myurl,
        id:'imageFile',
        success:function(res){
            alert(res);
        }
    });

});

function ajaxFileUpload(s){// 接收上传文件的后台地址,后台地址需要允许跨域传输操作
    var xhr = new XMLHttpRequest();
    var form=new FormData(),//表单对象
        target=document.getElementById(s.id);
    var file=target.files[0];
    form.append('file',file);
    xhr.open("post", s.url, true);//异步方式上传文件
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4){
            if(xhr.status==200){//上传成功返回回调信息xhr.responseT
                s.success(xhr.responseText);
            }
        }
    }
    xhr.send(form);//发送表单内容 
}

})();

</script>
</html>
[/code]
对应php代码:
[code]<?php
header('content-type:text/html;charset=utf8');
header('Access-Control-Allow-Origin: *');//允许所有主机跨域上传文件
//header('Access-Control-Allow-Methods: POST');
//接收文件的全局变量$_FILES
echo isset($_FILES);
//echo '<pre>';
//var_dump($_FILES);
print_r($_FILES);
//echo '</pre>';
//echo $_POST['file'];
if($_FILES['file']['tmp_name']){//上传成功,则移动到指定的文件夹内
if(move_uploaded_file($_FILES['file']['tmp_name'],'upload/'.$_FILES['file']['name'])){
echo '成功上传';
}else{
echo '没有找到目录';
exit;
}

}else{
    echo '没有上传成功';
}

?>[/code]


最新回复 (0)
返回