这篇文章主要为大家详细介绍了ajax实现异步文件(图片)上传功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
大家好,这篇文章我要给大家分享一个网页文件上传功能的代码,希望大家可以有所参考,或者给我提些建议。
众所周知现在的各大网站基本都设有文件上传功能,用户可以把自己喜欢的图片或其他文件放在网上存起来,以便以后用的时候方便去找,可是一个网页的文件上传功能究竟该怎么去设置呢?今天我就以图片上传为例向大家展示文件上传功能的具体步骤。
其实文件上传有两种方法,一种是from表单submit提交,一种是ajax实现异步提交,可是form表单提交有个问题就是每次在上传完成时会刷新界面,不能实现异步上传,所以现在几乎所有网站都采用ajax异步上传,现在我给大家展示ajax异步上传该如何实现。
首先我先创建一个form表单,代码如下:
<form action="" id="form">
用户名:<input type="text" name="user"/></br>
密码:<input type="password" name="pass" /></br>
性别:<input type="radio" name="sex" value="男"/>男
<input type="radio" name="sex" value="女"/>女
头像:<input type="file" id="file" name="file"/></br>
<button id="btn" type="button">提交</button>
</form>
<p class="con"></p>
创建完成后,首先我们要先拿到用户从本上传的图片的信息,代码如下
var imgs=[];//存储图片链接
//为文件上传添加change事件
var filem=document.queryselector("#file");
$("#file").on("change",function(){
console.log(filem.files);
//获取文件对象,files是文件选取控件的属性,存储的是文件选取控件选取的文件对象,类型是一个数组
var fileobj=filem.files[0];
//创建formdata对象,formdata用来存储表单的数据,表单数据时以键值对形式存储的。
var formdata=new formdata();
formdata.append('file',fileobj);
这里的formdata就是我们现在要的存储文件信息的对象,然后我们需要把它用ajax请求提交给后台:
//创建ajax对象
var ajax=new xmlhttprequest();
//发送post请求
ajax.open("post","http://localhost/phpclass/file-upload/move_file.php",true);
ajax.send(formdata);
ajax.onreadystatechange=function(){
if (ajax.readystate == 4) {
if (ajax.status>=200 &&ajax.status<300||ajax.status==304) {
console.log(ajax.responsetext);
var obj=json.parse(ajax.responsetext);
alert(obj.msg);
if(obj.err == 0){、
//上传成功后自动动创建img标签放在指定位置
var img =$("<img src='"+obj.msg+"' alt='' />");
$(".con").append(img);
imgs.push(obj.msg);
}else{
alert(obj.msg);
}
}
}
}
});
然后我们请求成功后,后台肯定要做出相应的处理,并且把图片存到指定的文件夹里,所以相应的php应该完成这些操作:
<?php
//解决跨域问题
header("access-control-allow-origin:*");
//说明向前台返回的数据类型为json
header("content-type:text/json");
//$_files超全局变量存储是文件数据,是一个关联数组
$fileobj=$_files['file'];
var_dump($fileobj);
if($fileobj["error"]==0){
//判断文件是否合法
$types=["jpg","jpeg","png","gif"];
$type = explode("/", $fileobj["type"])[1];
if(in_array($type, $types)){
$time = time();//获取时间戳 返回一个整形
//获取文件详细路径
$filepath="http://localhost/phpclass/image1".$time.".".$type;
echo $filepath;
//移动文件
$res=move_uploaded_file($fileobj["tmp_name"],"../image1/".$time.".".$type);
if($res){
$infor=array("err"=>0,"msg"=>"文件移动成功");
}else{
$infor=array("err"=>1,"msg"=>"文件移动失败");
}
}else{
$infor=array("err"=>1,"msg"=>"文件格式不合法");
}
echo json_encode($infor);
}
?>
这样我们就完成了文件上传的所有步骤,如果你想把自己喜欢的图片,上传到自己的网页上,希望这段代码可以帮助到你!
附:如果上传文件时还要附带上你的其它信息,你只需再前端页面请求完成后加上这段代码即可实现:
//完成form表单数据的提交
$('#btn').on('click',function(){
// serializearray()将form表单控件中的数据序列化成数组,数组中含有若干对象,对象包含对应控件的name和value
var infor = $('#form').serializearray();
// console.log(infor);
var stu = {};
for (var i=0;i<infor.length;i++) {
var obj=infor[i];
stu[obj.name] = obj.value;
}
stu["imgs"] = imgs;
stu["imgs"] = imgs[0];
//发送ajax请求
$.ajax({
url:"http://localhost/phpclass/file-upload/data.php",
data:{
parameter :json.stringify(stu)
},
success:function(res){
console.log(res.msg);
}
});
});
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
ajax用于判定用户是否注册
完美解决ajax跨域请求下parsererror的错误
用ajax传递json到前台中文出现问号乱码问题的解决办法
以上就是ajax实现异步文件或图片上传功能的详细内容。