第一步:在form表单中增加文件上传按钮:
如果要使用layui的按钮样式,需要先引入layui的CSS文件
第二步:JS处理部分
先引入layui.js
接下来有两部分:
一部分单独处理文件上传,文件上传成功后将文件地址填充到input的框里面.
//文件上传
layui.use('upload', function(){
var upload = layui.upload;
//执行上传
var uploadInst = upload.render({
elem: '#upload' //绑定元素
,url: '/web/ajax.php' //上传接口
,data: {gongneng:"upload"}//将所有的ajax处理放到同一个ajax.php中我这边以gongneng区分,你根据自己的需要区分即可.
,method: 'POST'
,accept: 'file'//接收的文件类型,根据自己的需要调整.
,size: 50//限制文件大小,根据自己的需要调整.
,before: function(obj){
layer.load();
}
,done: function(res){//上传完毕回调
layer.closeAll('loading');
//将返回的文件地址填充到input框中
$("input[name=file]").val(res.filename);
}
,error: function(){//请求异常回调
layer.closeAll('loading');
layer.msg('网络异常,请稍后重试!');
}
});
});
第二部分处理ajax表单提交.
$(document).ready(function(){
//判断Email正确性
function isEmail(email){
var patrn= /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
if (!patrn.exec(email)) return false;
return true;
}
//处理表单提交
$(".submit_btn").click(function(){
var that = this;
var form = $(that).parents('form');
var result = true;
form.find("input[type='text'],textarea").each(function(){
if(($(this).val()=="" || $(this).val()==null) && typeof($(this).attr("tip"))!="undefined"){
layer.tips($(this).attr("tip"),$(this));
$(this).focus();
result = false;
return false;
}
if($(this).attr("name")=="email" && !isEmail($(this).val())){
layer.tips($(this).attr("tip2"),$(this));
$(this).focus();
result = false;
return false;
}
})
if(result){
var classid = form.find("input[name=classid]").val();
var title = form.find("input[name=title]").val();
var username = form.find("input[name=username]").val();
var tel = form.find("input[name=tel]").val();
var company = form.find("input[name=company]").val();
var email = form.find("input[name=email]").val();
var file= form.find("input[name=file]").val();
var content = form.find("textarea[name=content]").val();
$.ajax({
type:"POST",
//dataType:"json",
url:"/web/ajax.php",
data:{
gongneng:"liuyan",
classid:classid,
title:title,
username:username,
tel:tel,
company:company,
email:email,
file:file,
content:content
},
success:function(result){
layer.msg(result);
},
error:function(){
layer.msg(result);
}
})
return false;
}else{
return false;
}
})
第三步:ajax.php中进行处理,也是分开处理,文件上传和表单提交
if($gongneng == "upload"){
//上传文件目录获取
$month = date('Ym',time());
define('BASE_PATH',str_replace('\\','/',realpath(dirname(__FILE__).'/'))."/");
$dir = BASE_PATH."upload/".$month."/";
//初始化返回数组
$arr = array(
'code' => 0,
'msg'=> '',
);
$file_info = $_FILES['file'];
$file_error = $file_info['error'];
if(!is_dir($dir))//判断目录是否存在
{
mkdir ($dir,0777,true);//如果目录不存在则创建目录
};
$file = $dir.$_FILES["file"]["name"];
if(!file_exists($file))
{
if($file_error == 0){
if(move_uploaded_file($_FILES["file"]["tmp_name"],$dir. $_FILES["file"]["name"])){
$arr['msg'] ="上传成功";
$arr['filename'] = "upload/".$month."/". $_FILES["file"]["name"];
}else{
$arr['msg'] = "上传失败";
}
}else{
switch($file_error){
case 1:
$arr['msg'] ='上传文件超过了PHP配置文件中upload_max_filesize选项的值';
break;
case 2:
$arr['msg'] ='超过了表单max_file_size限制的大小';
break;
case 3:
$arr['msg'] ='文件部分被上传';
break;
case 4:
$arr['msg'] ='没有选择上传文件';
break;
case 6:
$arr['msg'] ='没有找到临时文件';
break;
case 7:
case 8:
$arr['msg'] = '系统错误';
break;
}
}
}
else
{
//如果文件已经存在则重命名
$newfilename = rand(1,100).$_FILES["file"]["name"];
if(move_uploaded_file($_FILES["file"]["tmp_name"],$dir. $newfilename)){
$arr['msg'] ="上传成功";
$arr['filename'] = "upload/".$month."/".$newfilename;
}else{
$arr['msg'] = "上传失败";
}
}
echo json_encode($arr);
}
//通用表单提交
if($gongneng=='liuyan'){
$classid = $_POST["classid"] ? $_POST["classid"] : 1;
$title = $_POST["title"] ? $_POST["title"] : '首页或底部提交';
$username = $_POST["username"];
$company = $_POST["company"];
$tel = $_POST["tel"];
$email = $_POST["email"];
$file = $_POST["file"];
$content = $_POST["content"];
$thesql="insert into #@__feedback (classid,lanstr,title,tel,username,company,email,file,content,addtime,locked) values ($classid,'{$lanstr}','{$title}','{$tel}','{$username}','{$company}','{$email}','{$file}','{$content}',{$time},1)";
$db->dosql($thesql);
if($db->GetLastID()){
//如果成功
if($alz->getPiece("submit_success")){
echo $alz->getPiece("submit_success");
}else{
echo $alz->_lang("ok","feedback");
}
}else{
if($alz->getPiece("submit_error")){
echo $alz->getPiece("submit_error");
}else{
echo $alz->_lang("error","feedback");
}
}
}
小TIP:需要引入的是layui.js而不是layer.js哟.只引入layer.js是不能实现文件上传的.