# html:
```
点击上传,或将文件拖拽到此处
建议尺寸1920*512
提交
```
# JS:
```
layui.use('upload', function(){
var $ = layui.jquery
,upload = layui.upload;
//普通图片上传
var uploadInst = upload.render({
elem: '#uploadBanner'
,url: "{:U('Api/doUploadPic')}"
,before: function(obj){
//预读本地文件示例,不支持ie8
obj.preview(function(index, file, result){
$('#upload-photo').attr('src', result); //图片链接(base64)
$('#upload-photo').attr('style', 'height:10rem;');
$('#upload-icon').attr('style','display:none;');
});
}
,done: function(res, index, upload){
//如果上传失败
if(res.code > 0){
return layer.msg('上传失败');
}
//上传成功
console.log("成功啦!" + obj2string(res) + " " + index + " " + upload);
}
,error: function(){
//演示失败状态,并实现重传
var demoText = $('#demoText');
demoText.html('上传失败 重试');
demoText.find('.demo-reload').on('click', function(){
uploadInst.upload();
});
}
});
});
```
# PHP接口:
```
public function doUploadPic()//上传模块
{
$upload = new \Think\Upload();
$upload->maxSize = 3145728;
$upload->exts = array('jpg', 'gif', 'png', 'jpeg');
$upload->rootPath = './Public/'; // 设置附件上传根目录
$upload->savePath = 'upload/'; // 设置附件上传子目录
$info = $upload->upload();
if(!$info){
$this->error($upload->getError());
}else{
foreach($info as $file){
$data = '/Public'.$file['savepath'] . $file['savename'];
$file_a=$data;
echo '{"code":0,"msg":"成功上传","data":{"src":"'.$file_a.'"}}';
}
}
}
```
# 图片就上传到/Public/upload文件夹下了:
![](https://box.kancloud.cn/396b0c420b69820e47f9bdbccc1dd0e9_961x535.png)
![](https://box.kancloud.cn/396b0c420b69820e47f9bdbccc1dd0e9_961x535.png)
![](https://box.kancloud.cn/d99c5b16b1d25a22dcbacec7cd7ed753_753x352.png)
不需要点击提交,Layui下图片自动上传,回传上传图片的地址,然后提交到数据库,也就是伪提交
---------------------
作者:mencre
来源:CSDN
原文:https://blog.csdn.net/qq_17497931/article/details/81290604