layui上传模块文档链接: https://www.layui.com/doc/modules/upload.html
实例也很漂亮:https://www.layui.com/demo/upload.html
上传接口得自己设置,代码如下:
var uploadInst = upload.render({
elem: '#demo' //绑定元素
,url: 'upload.php' //上传接口
,done: function(res){
//上传完毕回调
}
,error: function(){
//请求异常回调
}
});
upload.php 代码如下:
$lastname=get_extension($_FILES["file"]["name"]);
$imgname = time().rand().".".$lastname;
$tmp = $_FILES["file"]["tmp_name"];
$size = $_FILES["file"]["size"];
$oldimg= '';
//图片尺寸不能超过3M
if($size==0 || $size/1024/1024>3){
echo '{ "errcode": 1 ,"msg": "'.$size.'" ,"data": { "src": "'.$imgname.'" } }';
}
else{
$filepath = getcwd()."/../../upload/image/";
$height = intval((getimagesize($tmp)[1]/getimagesize($tmp)[0])*110);
$img = "../../upload/image/".$imgname;
if(move_uploaded_file($tmp,$filepath.$imgname)){
echo '{ "errcode": 0 ,"msg": "'.$oldimg.'" ,"data": { "src": "'.$imgname.'" } }';
// //调整上传图片的大小
$lastname=strtolower($lastname);
thumb($img,$lastname);
}
}
//获取扩展名
function get_extension($file)
{
return pathinfo($file, PATHINFO_EXTENSION);
}
//用于对图片进行缩放
function thumb($filename,$lastname,$width=260,$height=160){
//获取原图像$filename的宽度$width_orig和高度$height_orig
list($width_orig,$height_orig) = getimagesize($filename);
//根据参数$width和$height值,换算出等比例缩放的高度和宽度
if ($width && ($width_orig<$height_orig)){
$width = ($height/$height_orig)*$width_orig;
}else{
$height = ($width / $width_orig)*$height_orig;
}
//将原图缩放到这个新创建的图片资源中
$image_p = imagecreatetruecolor($width, $height);
//获取原图的图像资源
if($lastname=="jpg" || $lastname=="jpeg"){
$image = @imagecreatefromjpeg($filename);
}
if($lastname=="png"){
$image = @imagecreatefrompng($filename);
}
if($lastname=="bmp"){
$image = @imagecreatefrombmp($filename);
}
if($lastname=="gif"){
$image = @imagecreatefromgif($filename);
}
//使用imagecopyresampled()函数进行缩放设置
imagecopyresampled($image_p,$image,0,0,0,0,$width,$height,$width_orig,$height_orig);
//将缩放后的图片$image_p保存,100(质量最佳,文件最大)
imagejpeg($image_p,$filename);
imagedestroy($image_p);
imagedestroy($image);
}