美文网首页
layUI图片上传 php代码

layUI图片上传 php代码

作者: DragonRat | 来源:发表于2018-11-28 19:24 被阅读0次

PHP代码

<?
error_reporting(0);
header("Content-Type:text/html;charset=utf-8");
//获取需要上传的文件目录
$temdir = $_GET["upfile"];
$uploaddir = "../style/upload/".$temdir;//设置文件保存目录 注意包含/       
$type=array("jpg","gif","bmp","jpeg","png","rar","zip","doc","docx","xls","xlsx");//设置允许上传文件的类型
$patch="/";//程序所在路径

//获取文件后缀名函数   
  function fileext($filename)   
{   
   return substr(strrchr($filename, '.'), 1);   
}   
//生成随机文件名函数       
function random($length)   
{   
  $hash = 'KJ-';   
 $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';   
 $max = strlen($chars) - 1;   
 mt_srand((double)microtime() * 1000000);   
       for($i = 0; $i < $length; $i++)   
     {   
          $hash .= $chars[mt_rand(0, $max)];   
     }   
  return $hash;   
}   
$a=strtolower(fileext($_FILES['file']['name']));   
//判断文件类型   
if(!in_array(strtolower(fileext($_FILES['file']['name'])),$type))   
 {   
 $text=implode(",",$type);   
    //echo "您只能上传以下类型文件: ",$text,"<br>"; 
    //echo $_FILES['file']['name'];
    exit("ERROR");
 }   
//生成目标文件的文件名       
else{   
$filename=explode(".",$_FILES['file']['name']);   
 do   
 {   
      $filename[0]=random(10); //设置随机数长度   
     $name=implode(".",$filename);   
        //$name1=$name.".Mcncc";   
     $uploadfile=$uploaddir.$name;   
  }   
while(file_exists($uploadfile));   
 if (move_uploaded_file($_FILES['file']['tmp_name'],$uploadfile)){ 
     //$uploadfile=str_replace("../","/",$uploadfile);
      $arr=array("code"=>1,"msg"=>"上传成功","src"=>$uploadfile);
       $myfile = fopen("file.txt", "w") or die("Unable to open file!");
     fwrite($myfile, $uploadfile);
      fclose($myfile);
   }
  else
   {
      
       $arr=array("code"=>0,"msg"=>"上传失败");

  } 
echo json_encode($arr);  
}    

?>

前台JS

layui.use('upload', function(){
  var upload = layui.upload;
  //上传文件
  var uploadInst = upload.render({
    elem: '#upfile' //绑定元素
    ,url: 'upload.php' //上传接口
    ,done: function(res){
if(res['code']==1){
//alert(res['src']);
var imgpath=res['src'];
//alert(imgpath);
layer.msg('图片上传成功');
$("#proimg").attr('src',imgpath);
$("#inputimg").val(imgpath);
}else{
layer.msg('图片上传失败');
}
 
    }
  });
});

相关文章

网友评论

      本文标题:layUI图片上传 php代码

      本文链接:https://www.haomeiwen.com/subject/glwzqqtx.html