Felix Maxime Felix Maxime - 1 month ago 9
PHP Question

Drop file upload coming up as null in Laravel

I've got a form with a drag and drop file input, which I originally found here:

http://codepen.io/prasanjit/pen/NxjZMO

the form is as follows:

<form method="POST" action="{{ url('images/save') }}">
<div class="file-drop-area">
<span class="fake-btn">Choose file</span>
<span class="file-msg js-set-number">or drag and drop file here</span>
<input class="file-input" type="file" name="fileUpload">
</div>
<button>Save</button>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>


the JS is unchanged from the original pen:

$(document).ready(function () {

var $fileInput = $('.file-input');
var $droparea = $('.file-drop-area');

// highlight drag area
$fileInput.on('dragenter focus click', function() {
$droparea.addClass('is-active');
});

// back to normal state
$fileInput.on('dragleave blur drop', function() {
$droparea.removeClass('is-active');
});

// change inner text
$fileInput.on('change', function() {
var filesCount = $(this)[0].files.length;
var $textContainer = $(this).prev('.js-set-number');

if (filesCount === 1) {
// if single file then show file name
$textContainer.text($(this).val().split('\\').pop());
} else {
// otherwise show number of files
$textContainer.text(filesCount + ' files selected');
}
});

});


The problem is, when I pass this through a controller, the file comes up as null when using

$file = $request->file('fileUpload');


however, when using

$file = $request->get('fileUpload');


and then die dumping $file, it turns out that the get request is actually getting the username. So it'll die dump something like "image01.jpg".

Furthermore, when adding validation to the form,

$this->validate($request, [
'fileUpload' => 'required',
]);


the form will only go through after you've attached a file.

So what's going on? Why is this coming up as null on a file request?

Answer
<form method="POST"  action="{{ url('images/save') }}" enctype="multipart/form-data">
Comments