Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

spook1's avatar

error in api Controller when adressing a file from formData.append

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..

0 likes
3 replies
SilenceBringer's avatar
Level 55

@spook1 you check one filename, and then use another one. do it like

if ($request->hasFile('imagefile')){
         
            $image = $request->file('imagefile'); 

			// imagefile, not picture
            $image_name = $request->file('imagefile')->getClientOriginalName(); 
spook1's avatar

O thanks. How silly... sorry for bothering you with this trivial question...

spook1's avatar

Now I have a new error when I try to save the image file...

 $image = $request->file('imagefile'); 
           // $image_name = strval(time().Str::random(5)).'.png'; //.$image->extension; /
            $image_name = $image->getClientOriginalName();
            $path = asset('storage/images/'.$image_name);

           
           $img = Image::make($image);
            $img->resize(300, 300, function ($constraint) {
                $constraint->aspectRatio();
            })->save($path);  

error in laravel logs:

[2021-08-15 09:48:09] local.ERROR: Can't write image data to path (http://localhost:8000/storage/images/testfile.png

I did do php artisan storage:link

the directory exists...

Should I make a new question forthis? Or can I ask you here?

Please or to participate in this conversation.