发布于:2020-04-17 10:56:42
// 应用公共文件
function fail($msg = '', $data = [])
{
return empty($data) ? json_encode(['statu' => 0, 'msg' => empty($msg) ? 'request fail.' : $msg], JSON_UNESCAPED_UNICODE) : json_encode(['statu' => 0, 'msg' => $msg, 'data' => $data], JSON_UNESCAPED_UNICODE);
}
function success($msg = '', $data = [])
{
return empty($data) ? json_encode(['statu' => 1, 'msg' => empty($msg) ? 'request success.' : $msg], JSON_UNESCAPED_UNICODE) : json_encode(['statu' => 1, 'msg' => $msg, 'data' => $data], JSON_UNESCAPED_UNICODE);
}
function warn($msg = '', $data = [])
{
return empty($data) ? json_encode(['statu' => 2, 'msg' => empty($msg) ? 'request warning.' : $msg], JSON_UNESCAPED_UNICODE) : json_encode(['statu' => 2, 'msg' => $msg, 'data' => $data], JSON_UNESCAPED_UNICODE);
}
function img_uploads($file,$tmp_path=null)
{
if (!empty($file)){
if (empty($tmp_path)){
$tmp_path = '/static/goods_img/';
}
$data_url = '';
//类型验证
$imagesExt=['jpg','png','git'];
if (is_array($_FILES['img']['type'])){
$data_url = null;
foreach ($_FILES['img']['error'] as $key => $val){
//跳过上传失败的图片
if ($_FILES['img']['error'][$val] == 0){
if ($_FILES['img']['size'][$key] > 2097152 ){
return warn('图片不得大于2M');
}
$ext = strtolower(pathinfo(@$_FILES['img']['name'][$key],PATHINFO_EXTENSION));
if (!in_array($ext,$imagesExt)){
return warn('非法文件类型');
}
$file_path = str_replace('\\','/',ROOT_PATH.$tmp_path);
if (!is_dir($file_path)){
mkdir($file_path,0777,true);
}
$file_name = md5(uniqid(microtime(true),true)).'.'.$ext;
$file_url = $file_path.$file_name;
if (!move_uploaded_file($_FILES['img']['tmp_name'][$key],$file_url)){
return warn('上传图片失败!');
}
$data_url[] = '/static/goods_img/'.$file_name;
}
}
}else{
//单图
if ($_FILES['img']['error'] == 0){
if ($_FILES['img']['size'] > 2097152 ){
return warn('图片不得大于2M');
}
$ext = strtolower(pathinfo(@$_FILES['img']['name'],PATHINFO_EXTENSION));
if (!in_array($ext,$imagesExt)){
return warn('非法文件类型');
}
$file_path = str_replace('\\','/',ROOT_PATH.$tmp_path);
if (!is_dir($file_path)){
mkdir($file_path,0777,true);
}
$file_name = md5(uniqid(microtime(true),true)).'.'.$ext;
$file_url = $file_path.$file_name;
if (!move_uploaded_file($_FILES['img']['tmp_name'],$file_url)){
return warn('上传图片失败!');
}
$data_url[] = $tmp_path.$file_name;
}
}
return success('success',$data_url);
}else{
return warn('文件不得为空');
}
}
多图input格式:
<input type=file name="img[]" multiple><br>
调用:
//图片上传接口
public function img_upload(){
if (!empty($_FILES)){
return img_uploads($_FILES);
}
}
阅读 412+
10