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.
CodePudding user response:
Try stringify data before sending like this:
$.ajax({
...
data: {fd: JSON.stringify(fd),
...
CodePudding user response:
you need to add multipart form data
contentType: "multipart/form-data",