用ajax提交一组表单,里面包含一个图片,
原来不用ajax提交的时候可以成功保存到数据库,
但因为上传前要压缩图片,所以改为ajax提交,ajax请求成功发送,但不能保存到数据库,
我想可能是控制器里面的代码需要修改,但不知怎么改,下面是代码。
ps:压缩图片用到了localResizeIMG插件。https://github.com/think2011/localResizeIMG
下面是用ajax提交表单的视图:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<link href="https://cdn.bootcss.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.bootcss.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet">
</head>
<body>
<p class="container">
<fieldset class="form-group">
<label for="title">标题</label>
<input type="text" class="form-control" id="title" placeholder="">
</fieldset>
<fieldset class="form-group">
<label for="content">内容</label>
<textarea class="form-control" id="content" rows="3"></textarea>
</fieldset>
<fieldset class="form-group">
<label for="photo">图片</label>
<input type="file" name="file" accept="image/*" class="form-control-file" id="photo">
<img id="preview"/>
</fieldset>
<a id="submit" class="btn btn-primary">提交</a>
</p>
<script src="https://cdn.bootcss.com/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/tether/1.1.1/js/tether.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js"
integrity="sha384-vZ2WRJMwsjRMW/8U7i6PWi6AlO1L79snBrmgiDpgIWJ82z8eA5lenwvxbMV1PAh7"
crossorigin="anonymous"></script>
//用了localResizeIMG插件,用于上传图片前先压缩。https://github.com/think2011/localResizeIMG
<script src="js/dist/lrz.all.bundle.js"></script>
<script>
$(function () {
var $preview = $('#preview');
var formData = null;
$('#photo').on('change', function () {
lrz(this.files[0], {
width: 800
}).then(function (rst) {
$preview.attr('src', rst.base64);
rst.formData.append('fileLen', rst.fileLen);
});
});
$("#submit").click(function (rst) {
$.ajax({
type: "POST",
url: "article/",
dataType: 'json',
cache: false,
data: {
title: $("#title").val(),
content: $("#content").val(),
photo: rst.formData
}
}).done(function (msg) {
alert("done: " + msg);
}).fail(function (jqXHR, textStatus) {
alert("fail: " + textStatus);
});
});
});
</script>
</body>
</html>
下面是原来没用ajax时候的控制器,可以成功保存到数据库,现在不知怎么改。
public function store(Requests\StoreArticleRequest $request)
{
$article = new Article($request->except('photo'));
$article -> user_id = \Auth::id();
$file = $request->file('photo');
$destinationPath = 'uploads/';
$extension = $file->getClientOriginalExtension();
$fileName = \Auth::user()->id . '_' . time() . '.' . $extension;
$file->move($destinationPath, $fileName);
$article -> photo = '/'.$destinationPath.$fileName;
$article->save();
return redirect()->action('ArticleController@show', ['id' => $article->id]);
}
下面是StoreArticleRequest
public function rules()
{
return [
'title'=>'required',
'content'=>'required',
'photo'=>'image'
];
}
save
前你先dd
下$article
数据看看csrf,ajax提交的时候不要忘。