GrantLS's avatar

Uploaded file not found by controller

Hello all, I have a Laravel app that is responsible for storing uploaded files. I am working on the code for uploading and storing files. I've run into a snag in which my controller can't see any uploaded files in the request object.

I have a basic check for the file in a controller method:

public function store(Request $request)
{
   if(!$request->hasFile('fileToUpload')){
     app()->abort(500, 'File upload missing');
    }
}

This always throws a 500. I have confirmed by looking at the headers in my browser that the file is indeed being sent to the server.

I'm wondering whether this has to do with /tmp directory permissions but my permissions look OK:

# ls -ald /tmp
drwxrwxrwt 1 root root 4096 Apr  9 23:56 /tmp

Any insight into why this is happening? It's a Laravel 10.x app running via Sail.

0 likes
8 replies
tykus's avatar

Why oh why do you abort with a 500 server error if the code suggests that the user did not upload a file; there are Validation Rules for this sort of check!?!

What does the form markup look like; do you have the enctype="multipart/form-data" attribute on the form element?

1 like
GrantLS's avatar

@tykus I'm only aborting with a 500 for the purposes of debugging this issue. Yes, the form has enctype="multipart/form-data"

GrantLS's avatar

@tykus I was posting it with JS via the fetch API using a FormData object. I switched it to just a plain form and it works so the problem is not with Laravel but with my front end code. Thanks for your help.

tykus's avatar

@GrantLS okay, so do you need some help with the Fetch / FormData part?

GrantLS's avatar

@tykus Thanks but I figured it out. I was manually setting Content-Type: multipart/form-data in the fetch headers, which, according to MDN, "will prevent the browser from being able to set the Content-Type header with the boundary expression it will use to delimit form fields in the request body."

2 likes
Tray2's avatar

My guess is that you have forgotten the multipart/form-data attribute in your form.

<form action="/upload" method="post" enctype="multipart/form-data"> 

Or the name of the field.

<input type="file" name="fileToUpload">
1 like

Please or to participate in this conversation.