如果你对该文章中的内容有疑问/不解,可以点击此处链接提问
要注明问题和此文章链接地址 点击此处跳转
<!--html--> <button type="button" class="layui-btn" id="up_pic">上传图片</button> <input class="input pic_input" type="text" size="40" name="thread[pic]" id="contentPic" /> <img class="layui-upload-img" id="demo1" src=""> <!--jq--> <script type="text/javascript"> layui.use('upload', function(){ var $ = layui.jquery ,upload = layui.upload; //普通图片上传 var uploadInst = upload.render({ elem: '#up_pic' ,url: '__APP__/public/upload2.html' ,before: function(obj){ //预读本地文件示例,不支持ie8 obj.preview(function(index, file, result){ $('#demo1').attr('src', result); //图片链接(base64) }); } ,done: function(res){ //如果上传失败 if(res.code > 0){ return layer.msg('上传失败'); } $('#contentPic').val('/'+res.url); //上传成功 } ,error: function(){ //演示失败状态,并实现重传 var demoText = $('#demoText'); demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>'); demoText.find('.demo-reload').on('click', function(){ uploadInst.upload(); }); } }); }); </script> <!--php--> public function upload2(){ // echo "<pre>"; // var_dump($_FILES);die; $fileName = $_FILES['file']['name'];//文件名 $tmpName = $_FILES['file']['tmp_name'];//临时存放的目录 $fileError = $_FILES['file']['error']; $fileType = $_FILES['file']['type']; $fileSize = $_FILES['file']['size']; if($fileError>0){ switch($fileError){ case 1: echo "上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值"; break; case 2: echo "上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值"; break; case 3: echo "文件只有部分被上传"; break; case 4: echo "没有文件被上传"; break; case 6: echo "找不到临时文件夹。PHP 4.3.10 和 PHP 5.0.3 引进"; break; case 7: echo "文件写入失败。PHP 5.1.0 引进"; break; } } $ext = pathinfo($fileName,PATHINFO_EXTENSION);//类型 $saveName = date('Ymd').mt_rand(1,100).'.'.$ext; //生成保存路径 $uploads = "uploads/"; $path = rtrim($uploads,'/')."/".date('Y/m/d/'); if(!file_exists($path)){ mkdir($path,0777,true); } $saveFile = $path .$saveName; if(move_uploaded_file($tmpName,$saveFile)){ // echo "上传成功"; $ret['message']="成功"; $ret['status'] = 1; $ret['url'] = $saveFile; echo json_encode($ret); }else{ // echo "上传失败啊"; $ret['message']="失败"; $ret['status'] = 0; echo json_encode($ret); } }