0

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: enter image description here

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.

Felix
  • 2,532
  • 5
  • 37
  • 75
  • 1
    what's is in AJAX's payload? – Ali Raza Dec 31 '22 at 04:52
  • In the console.log(fd) you already see, that `file -> {}`, so it isn't filled. In your `fd.append('file',files[0]);`, see if you get something from `files[0]`, this is purely debugging. What is in `var files`, for example? – UnderDog Dec 31 '22 at 04:58
  • @UnderDog console.log(files); returns the following: FileList [ File ] ​ 0: File { name: "Untitled.png", lastModified: 1672461379071, size: 17639, … } ​ length: 1 – Felix Dec 31 '22 at 05:13
  • @AliRaza how can I show you the payload? – Felix Dec 31 '22 at 05:23
  • 1
    Using the network tab in dev tools for your browser: e.g: https://stackoverflow.com/questions/15603561/how-can-i-debug-a-http-post-in-chrome – Ali Raza Dec 31 '22 at 05:29
  • @AliRaza the payload part just says [object Object]. Strange. – Felix Dec 31 '22 at 05:36
  • What does `$request->files()->all()` return? – Sachin Bahukhandi Dec 31 '22 at 05:43

3 Answers3

1

Try stringify data before sending like this:

$.ajax({
  ...
  data: {fd: JSON.stringify(fd),
  ...
Ali Raza
  • 842
  • 7
  • 13
  • Doesn't work. Request payload is still just [object Object]. I also tried removing processData: false, since you're stringifying but that didn't work either. – Felix Dec 31 '22 at 05:50
1

you need to add multipart form data

contentType: "multipart/form-data",
0

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.

Felix
  • 2,532
  • 5
  • 37
  • 75