This is my ajax request:
var files = $('#imgur_attach')[0].files;
if(files.length > 0){
var fd = new FormData();
// Append data
fd.append('file',files[0]);
fd.append('_token',$globalToken);
$.ajax({
type: "POST",
dataType: "json",
contentType: false,
processData: false,
url: host + "/attach-comment-image/" ,
data: {fd},
Controller:
public function attach(Request $request) {
$this->validate($request, [
'file' => 'image|required',
]);
When sending this ajax request, the validator tells me that the "file" field is required. Trying to return request->get('file')
returns null
.
However, when I do console.log(fd);
before the ajax request, it returns the following:
Why is this happening? I don’t normally upload files with AJAX over a regular POST request, so I don’t understand what I’m missing.
3
Answers
Wrapping the input around with a form tag like this did the trick:
Not sure why setting
contentType: "multipart/form-data"
in the ajax request doesn't work, but this solution works so I'll just use this instead.Try stringify data before sending like this:
you need to add multipart form data