Reputation: 2661
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.
Upvotes: 0
Views: 442
Reputation: 2661
Wrapping the input around with a form tag like this did the trick:
<form method="POST" enctype="multipart/form-data">
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.
Upvotes: 0
Reputation: 70
you need to add multipart form data
contentType: "multipart/form-data",
Upvotes: 1
Reputation: 932
Try stringify data before sending like this:
$.ajax({
...
data: {fd: JSON.stringify(fd),
...
Upvotes: 1