Html5&Ajax实现文件后台上传

4 篇文章 0 订阅
2 篇文章 0 订阅

通过表单上传文件(http://www.w3school.com.cn/php/php_file_upload.asp)在某些情况下已经不实用了(比如网页聊天室发送图片),经过几个小时的摸索,以下代码运用HTML5的FormData类和Ajax技术实现了后台的文件上传


html文件:index.html

<html>

<head>

</head>

<body>

<input type = 'file' id = 'file'/>

<!-- 
<input type = 'file' id = 'file' multiple />
如果这样写,就可以选中多个文件
都在document.getElementById("file").files数组里
-->

<button onclick = 'aa()'> ZZZ </button>

<script>

function GetXmlHttpObject()
//根据不同浏览器获取XmlHttp对象
{
	var xmlHttp=null;
	try
	{
 // Firefox, Opera 8.0+, Safari
	xmlHttp=new XMLHttpRequest();
	}
	catch (e)
	{
	// Internet Explorer
	try
	{
	xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch (e)
		{
		xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
 return xmlHttp;
}

function aa()
{
	var xx = document.getElementById("file").files[0];
	
	var fd = new FormData() //FormData 顾名思义,表单也
	
	//表单中添加项,当然也可以添加别的,比如 fd.append('author', 'kkk')
	fd.append('file', xx) 

	var xhr = GetXmlHttpObject();//这里不直接用new XMLHttpRequest()避免浏览器不兼容
	if (xhr == null)
	{
		alert ("Browser does not support HTTP Request")
		return
	} 
	
	//注意!! 如果fd的append的值是文件
	//在trans.php中$_POST数组将看不到该属性
	//而应该在$_FILES中查看!!
	xhr.open("POST" ,"./trans.php" , true);
	
	xhr.send(fd);
	
	xhr.onload = function(e) {
	
		if (this.status == 200) {
		
		   alert(this.responseText);
		   //由trans.php将上传的文件属性传过来,仅作参考
		}
	
	};
}
	
</script>

</body>

</html>


php文件 trans.php

<?php

	//将PHP临时文件夹创建的副本剪切为第二个参数所指的文件
	move_uploaded_file($_FILES["file"]["tmp_name"], "file/" . $_FILES["file"]["name"]);

	print_r ($_FILES);

?>

新建名称为“file”的文件夹,上述代码将选中的文件复制到该文件夹中。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值