ajax表单上传图片和数据
2021-05-01 08:28
标签:add 文件上传 href style extends sda lse pat 单位 js 控制器 模型 验证器 ajax表单上传图片和数据 标签:add 文件上传 href style extends sda lse pat 单位 原文地址:https://www.cnblogs.com/zhangcheng001/p/12147044.html $(‘#addbtn‘).click(function () {
var form = document.getElementById("img-form");//获取表单的数据
var formdata = new FormData(form);//格式化表单数据
console.log(formdata);
$.ajax({
type: "POST",
async:false,//同步请求
processData: false,// 不处理发送的数据
contentType: false,// 不设置Content-Type请求头
dataType: "json",
url: "{:url(‘admin/banner/upload‘)}",
data: formdata,
success: function (res) {
if (res.code == 1) {
layer.msg(res.msg, {
icon: 6,
time: 2000
}, function () {
window.location.href = res.url;
})
} else {
layer.open({
title: ‘添加失败‘,
content: res.msg,
icon: 5,
anim: 6
})
}
}
});
})
// 上传图片
public function upload()
{
if (request()->isPost()) {
$data = [
‘title‘ => input(‘title‘),
‘desc‘ => input(‘desc‘),
‘link‘ => input(‘link‘)
];
$file = request()->file(‘image‘);
if (!$file) {
$this->error($file->getError());
}
//验证
$map = [
‘ext‘ => ‘jpg,png,bmp,jpeg,gif‘,
‘size‘ => ‘3000000‘ //3MB 文件大小单位是字节
];
$info = $file->validate($map)->move(ROOT_PATH . ‘public‘ . DS . ‘uploads‘);
if (!$info) {
$this->error($file->getError());
}
$data[‘path‘] = DS . ‘uploads‘ . DS . $info->getSaveName();
$res = model(‘Banner‘)->upload($data);
if ($res == 1) {
$this->success(‘添加成功!‘, ‘admin/banner/bannerlist‘);
} else {
$this->error($res);
}
}
}
class Banner extends Model
{
//文件上传
public function upload($data)
{
$validate = new ValidateBanner();
if (!$validate->scene(‘upload‘)->check($data)) {
return $validate->getError();
}
$res = $this->allowField(true)->save($data);
if ($res) {
return 1;
} else {
return ‘上传失败!‘;
}
}
}
class Banner extends Validate
{
protected $rule = [
‘title|标题‘ => ‘require‘,
‘link|链接‘ => ‘require‘,
‘desc|描述‘ => ‘require‘
];
protected $scene = [
‘upload‘ => [‘title‘, ‘link‘, ‘desc‘]
];
}
上一篇:前端面试题--HTTP
下一篇:@Aspect 拦截器相关