我有一个Vue表单,可以上传带有图片的用户帖子。在axios帖子中添加新帖子时,似乎出现了故障,所有数据在确认之前。我没有返回json数据,成功正在触发。这是vue提交功能。
submit() {
let formData = new FormData();
formData.append('description', this.form.description)
formData.append('media', this.input.image)
if (this.$refs.form.validate()) {
this.loading = true
axios.post('/posts',
formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(res => {
this.$toast.success('You have added a post')
this.$emit('success', res.data)
})
.catch(err => {
this.handleErrors(err.response.data.errors)
})
.then(() => {
this.loading = false
})
}
}
添加帖子的api路线如下
Route::post('posts', 'PostController@store');
这是PostController上的store方法
public function store(Request $request)
{
$extension = $request->file->getClientOriginalExtension();
$filenameWithExt = $request->file->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$fileNameToStore = $filename.'_'.time().'.'.$extension;
$request->file->storeAs('public/uploads', $fileNameToStore);
$media_type = 0;
$supported_image = array(
'gif',
'jpg',
'jpeg',
'png'
);
$supported_video = array(
'mp4',
'mov',
'm4v'
);
$ext = strtolower($extension);
if(in_array($ext, $supported_image)) {
$media_type = 1;
}
elseif(in_array($ext, $supported_video)) {
$media_type = 2;
}
//add new post
$post = New Post;
$post->user_id = $this->user->id;
$post->description = $request->description;
$post->media = $fileNameToStore;
$post->media_type =$media_type;
if ($this->user->post()->save($post))
return response()->json([
'success' => true,
'post' => $post
]);
else
return response()->json([
'success' => false,
'message' => 'Sorry, post could not be added.'
], 500);
}