html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content=""/>
<meta name="keywords" content=""/>
<meta name="viewport" content="initial-scale=1, maximum-scale=3, minimum-scale=1, user-scalable=no">
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
<div class="wrapper">
<form action="/upload.php" enctype="multipart/form-data" method="post" id="form-import">
<div class="item">
<div class="outer">
<div class="form-group group-top">
<div class="form-line">
<label for="">默认csv</label>
<input type="file" class="input" name="file" id="file">
<div class="btn" id="upload">上传</div>
<span class="upload-info"></span>
</div>
</div>
</div>
</div>
</form>
</div>
<script src="/static/js/jquery.min.js"></script>
<script src="/static/js/jquery.form.js"></script>
<script>
$(function() {
var uploaded = false;
var filename = '';
$("#upload").click(function () {
if(!uploaded) {
uploaded = true;
$('.upload-info').text('正在上传,请稍候...');
$("#form-import").ajaxSubmit({
url: 'upload.php', /*设置post提交到的页面*/
type: "post", /*设置表单以post方法提交*/
dataType: "json", /*设置返回值类型为文本*/
success: function (ret) {
if(ret.status == 200) {
filename = ret.data;
$('.upload-info').text('上传成功!');
}else{
$('.upload-info').text('上传失败!');
alert(ret.message);
}
uploaded = false;
},
error: function (error) {
uploaded = false;
alert('服务器错误或网络错误');
$('.upload-info').text('');
},
});
}
});
})
</script>
</body>
</html>
upload.php
<?php
if(!isset($_FILES["file"])) {
ajax_return('请选择文件', 500);
}
// 允许上传的后缀
$allowedExts = array("csv");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp); // 获取文件后缀名
if (($_FILES["file"]["size"] < 1024*1024*20) // 小于 20mb
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
$message = "错误:: " . $_FILES["file"]["error"];
}
else {
$filename = md5(uniqid(microtime())).'.'.$extension;
// 判断当期目录下的 upload 目录是否存在该文件
if (file_exists("upload/" . $filename)) {
$message = $filename . " 文件已经存在。 ";
}
else {
// 如果 upload 目录不存在该文件则将文件上传到 upload 目录下
$ret = move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $filename);
if($ret) {
$message = "文件存储在: " . "upload/" . $filename;
ajax_return($message, 200, $filename);
}else{
$message = "上传失败";
}
}
}
}
else {
$message = "非法的文件格式";
}
ajax_return($message, 500);
/* ajax接口返回
*
* @author fangdong
* @param mixed $data
* @param boolean $status
* @param String $message
*/
function ajax_return($message, $status, $data = null)
{
//ob_clean();
$r = array(
'message' => $message,
'status' => $status,
'data' => $data,
);
header('Content-Type:application/json;charset=utf-8');
exit(json_encode($r));
}