部分
<div class="layui-form-item">
<label class="layui-form-label">上传图片</label>
<div class="layui-input-inline">
<div class="layui-upload">
<button type="button" class="layui-btn" id="btn_main">上传图片</button>
<div class="layui-upload-list main_img">
<img src="{$info['img'] ?? ''}" class="layui-upload-img upload-img" id="main_img">
</div>
</div>
</div>
</div>
js部分
var uploadInst = upload.render({
elem: '#btn_main'
,url: '/common/upload/layupload'
,field: 'img'
,done: function(res){
console.log(res)
if(res.code < 0){
return layer.msg(res.msg);
}
$('.main_img').html('<img src="/public/'+res.path+'" class="layui-upload-img upload-img" id="main_img">');
}
});
php部分
public function layUpload()
{
if(!$this->request->isPost()) return show(config("status.error"), '非法请求');
//上传文件目录获取
$month = date('Ym', time());
$dir = app()->getRootPath(). "public/topic/" . $month . "/";
$filename = $_FILES["img"]["name"];
$newname = explode('.',$filename);
$newname = time().'.'.array_pop($newname);
//初始化返回数组
$imgsrc = $dir . $newname;
$returnname = explode('public',$imgsrc);
$file_info = $_FILES['img'];
$file_error = $file_info['error'];
if (!is_dir($dir)) //判断目录是否存在
{
mkdir($dir, 0777, true); //如果目录不存在则创建目录
};
// $file = $dir . $_FILES["file"]["name"];
if ($file_error == 0) {
if (move_uploaded_file($_FILES["img"]["tmp_name"], $dir . $newname)) {
return json(['code' => 1, 'path' => $returnname[1]]);
} else {
$errormsg = "上传失败";
}
} else {
switch ($file_error) {
case 1:
$errormsg = '上传文件超过了PHP配置文件中upload_max_filesize选项的值';
break;
case 2:
$errormsg = '超过了表单max_file_size限制的大小';
break;
case 3:
$errormsg = '文件部分被上传';
break;
case 4:
$errormsg = '没有选择上传文件';
break;
case 6:
$errormsg = '没有找到临时文件';
break;
case 7:
case 8:
$errormsg = '系统错误';
break;
}
}
return json(['code' => 0, 'msg' => $errormsg]);
}