用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提交的時候不要忘。