您好我有一个Laravel博客应用程序,并希望在我的帖子下添加图片。我已阅读Laravel Storage文档,查看了几个教程和讨论,但我仍然非常困惑。我正在尝试将图像保存到存储文件夹以及稍后要检索的数据库路径。我使用php artisan storage:link
链接了我的存储文件。我得到的错误是Call to a member function store() on null
这是我的HTML和ajax调用:
@section('content')
<div class="container">
<div class="row">
<h1>Create your post</h1>
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" id="title" class="form-control">
</div>
<div class="form-group">
<label for="post">Post</label>
<textarea name="post" rows="8" cols="80" id="post" class="form-control"></textarea>
</div>
<div class="form-group">
<label for="image">Add image</label>
<input type="file" name="image" id="image" class="form-control">
</div>
<input type="submit" name="submit" value="Submit Post" id="submit" class="btn btn-primary">
</div>
</div>
<script>
$(document).ready(function(){
$("#submit").on("click", function(e){
e.preventDefault();
var title = $("#title").val();
var post = $("#post").val();
var image = $("#image").val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr("content")
}
});
$.ajax({
url:'/post/create/create',
type: "POST",
data: {
title: title,
post: post,
image: image,
},
success:function(response){
toastr.success(response.response);
},
error: function(error){
toastr.error(error.error)
}
});
});
});
</script>
@endsection
这是我的帖子控制器:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use App\User;
use App\Comment;
use Auth;
class PostController extends Controller{
public function create(Request $request){
$this->validate($request, [
'title' => 'required',
'post' => 'required',
]);
$path = $request->file('image')->store('images');
$post = new Post;
$post->title = $request->input('title');
$post->post = $request->input('post');
$post->uploadImage = $path;
$post->user_id = Auth::user()->id;
$post->save();
$response = [
'response' => 'Post Created Successfully',
'error' => 'Something went wrong'
];
return response()->json($response);
}
}
答案 0 :(得分:0)
要使用ajax
上传图片,您必须使用FormData
,如:
var formData = new FormData();
var fileData = $('#image').prop('files')[0];
var name = $('#name').val();
formData.append('fileData', fileData);
formData.append('name', name);
并在ajax中使用它:
$.ajax({
url: 'your url',
method: 'post',
data: formData,
contentType : false,
processData : false,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(response){
// yoou code here
}
});
在服务器端,您可以获得formData
,并且所有附加值都可以在各自的索引中找到。