99行代码(HTML+js+php)实现ajax上传文件并保存,不依赖其他函数比如jq;
支持上传前后都进行后缀和文件大小判断;
支持修改参数设定可上传文件大小及可上传后缀。
<?php
$isup = ".csv|.txt|.jpg|.gif|.rar|.zip|.doc|.xls|.xlsx"; //修改可上传格式
$lenx = 500; //修改上传文件最大值,单位KB
function getext($file){
$info = pathinfo($file);
return $info['extension'];
}
if($_GET["act"]=="up"){
$path=$_POST["tim"];
$base=$_POST["txt"];
//可加入文件大小 和 格式判断
$tape = getext($path);
if(!stristr("|{$isup}|","|.{$tape}|")){ exit("上传失败,文件名后缀[{$tape}]不支持!");}
$txts=explode("base64,",$base);
$txto=base64_decode(str_replace(" ","+",$txts[1]));
if(strlen($txto)>$lenx*1024){ exit("上传失败,文件大小超过允许值{$lenx}KB!");}
$files = date("YmdHis").".".$tape;
file_put_contents($files, $txto);
exit($path."上传成功,更名为:".$files);
}
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax File upload</title>
<style>
</style>
<script>
var $=function(node){
return document.getElementById(node);
}
function $(objId){
return document.getElementById(objId);
}
function GetRequest(Url,GetFunction){
if(window.ActiveXObject){
var xpost = new ActiveXObject("Microsoft.XMLHTTP");
}else{
var xpost = new XMLHttpRequest();
}
xpost.onreadystatechange = function(){
if(xpost.readyState == 4){
if(xpost.status == 200){
GetFunction(xpost.responseText);
}else{
GetFunction(404);
}
}else{
GetFunction("载入中...");
}
}
xpost.open("post",'?act=up',true);
xpost.setRequestHeader("Content-type","application/x-www-form-urlencoded;charset-UTF-8");
xpost.send(Url);
}
window.onload = function () {
var input = $("fielinput");
if (typeof (FileReader) === 'undefined') {
$("tips").innerHTML = "抱歉,请使用chrome,firefox等现代浏览器,国产浏览器请使用急速模式!";
input.setAttribute('disabled', 'disabled');
} else {
input.addEventListener('change', readFile, false);
}
}
function readFile() {
var file = this.files[0];
if (file.size>1) {
$("fielinput").value=""; //初始化防止上传同名无反应
if (!/(<?php echo $isup; ?>)$/.test(file.name)){
$("tips").innerHTML = "上传失败:该后缀格式不支持上传!";
return false;
}
if (file.size><?php echo $lenx; ?>*1024) {
$("tips").innerHTML = "上传失败:文件大小请控制在<?php echo $lenx; ?>kB以内!";
return false;
}
var reader = new FileReader();
reader.readAsDataURL(file);//readAsText(file,"UTF-8")
reader.onload = function (e) {
SendUrl = "tim="+file.name+"&txt="+this.result;
GetRequest(SendUrl,function(GetText){
if(GetText == 404){
$("tips").innerHTML = "上传失败!";
return false;
}else{
$("tips").innerHTML = GetText;
}
});
}
}
}
</script>
</head>
<body>
<p><input type="file" id="fielinput" /></p>
<div id="tips"></div>
</body>
</html>
|