File upload does not work Laravel
12,276
To send files using POST
request, you need change encode of form to multipart/form-data
. More details: HTML <form> enctype Attribute.
Without enctype
data form send only some details about file.
Author by
Sander Van Keer
Updated on June 07, 2022Comments
-
Sander Van Keer almost 2 years
I'm trying to upload an image from a form and store it in my laravelproject. The folder I want to store these pictures in is calles battlePics and I made this folder on the assets level. The actual problem is that $filename remains empty after this function. This is my controller:
if (Input::hasFile('file')) { $file = input::get('file'); $string = str_random(40); $filename = hash("md5", $string) . $file->getClientOriginalName(); $file->move('battlePics', $filename); $battle->picture = $filename; } $battle->save();
I use the md5 hash to create different filenames to avoid errors when an image with the same name is uploaded. Here is the view of my form:
<form id="battleForm" class="battleForm" action="" method="post" role="form"> <input type="hidden" name="userID" value="{{Auth::id()}}"> <div class="form-group"> <label for="title">Title of the battle?</label><br> <input type="text" id="title" name="title" placeholder=""><br> </div> <div class="form-group"> <label for="points">Points to be earned</label><br> <input type="text" id="points" name="points" placeholder=""><br> </div> <div class="form-group date"> <label for="startdate">Startdate</label><br> <input type="date" id="startdate" name="startdate" placeholder=""><br> </div> <div class="form-group date"> <label for="enddate">Enddate</label><br> <input type="date" id="enddate" name="enddate" placeholder=""><br> </div> <div class="form-group"> <label for="description">What is the battle about?</label><br> <textarea type="text" id="description" name="description" placeholder=""></textarea><br> </div> <div class="form-group radiobuttons"> <label for="group1">Want to start de battle right away?</label><br> <ul> <li><input class="radiobattle" type="radio" name="active" value="yes"> <span>yes</span></li> <li><input class="radiobattle" type="radio" name="active" value="no"><span>no</span><br></li> </ul> </div> <div class="form-group battleimg uploadbatlle field"> <img id="previewNewFile" src="" style="height:100px; width:150px;display: none; " required="true"/> <input style="" type="file" name="file" id="file" required="true"> </div> <br> <input type="submit" name="battleSubmit" class="battleSubmit" value="Add new Battle"><br> <input type="hidden" class="tokenReferEmail" name="_token" value="<?php echo csrf_token(); ?>"> </form>
I really hope you guys can help me.
-
Sander Van Keer over 8 yearsThis was half of the solution. I also had to change the: $file = input::get('file'); to Input::File('file');