In a VUe.js form I build and upload a formData to process in the api controller.
addCard(){
const formData = new FormData();
formData.append('title',this.card.title);
formData.append('description',this.card.description);
formData.append('imagefile',this.selectedFile);
console.log(formData.get('imagefile').name);
//add
fetch(`api/cards`, {
method: 'post',
body:formData,
headers:{
//'content-type': 'multipart/form-data',
// 'accept':'application/json'
}
})
.then(res => console.log(res))
//.then(res => res.formData())
.then(data => {
this.card.title='';
this.card.description='';
this.card.picture='';
alert('Card added');
this.fetchCards();
})
.catch(err => console.log(err));
}
The api controller works ok, as lomg as I negelct the file.
In the api Controller I get errors as soon as I try to do something with the file.
for instance: when I ask for the name of the file I get the error:
Error: Call to a member function getClientOriginalName() on null in file
The relevant controller script is:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Card;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
class CardController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$cards = Card::all()->toArray();
//return $cards;
return array_reverse($cards);
//return Card::orderBy('created_at', 'desc')->paginate(2);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
logger($request->all());
//validate data first
$request->validate([
'description'=> 'required'
]);
$card = $request->all();
if ($request->hasFile('imagefile')){
$image = $request->file('picture');
//WHEN THIS LINE IS ADDED ERRORS OCCUR:
$image_name = $request->file('picture')->getClientOriginalName();
The cause is probably trivial, since I am new to laravel and vue, I may have not set up the configuration correctly..
Can it be I have install additional dependencies or something?
The laravel logger logger($request->all()); returns:
[2021-08-15 08:34:04] local.DEBUG: array (
'title' => 'test_title',
'description' => 'test',
'_method' => 'PUT',
'imagefile' =>
Illuminate\Http\UploadedFile::__set_state(array(
'test' => false,
'originalName' => 'klein.png',
'mimeType' => 'image/png',
'error' => 0,
'hashName' => NULL,
)),
so I think that the file is actually transferred to the controller.
Somehow it isnot recognized..