简体   繁体   中英

appendin data fto formData ,the object is empty

In this code I send the formdata on an ajax request but the $_POST array is empty on the destination file

('#uploadImgForm').submit(function(e){
        e.preventDefault();
        var files = $('#selectedFiles')[0].files;
        var correct = true;
        var form = $(this);
        var data = new FormData();

        //si contiene ficheros
        if(files.length > 0){
            Array.from(files).forEach(file => {
            var filename = file.name.toLowerCase();


            //recorrer los ficheros para comprobar que son imagenes
            if(!(/^.+\.(gif|jpg|jpeg|png)$/i).test(filename))
                correct = false;
            else{
                data.append(filename, file);

            }
        });

            console.log(data);
            //si todos son imagenes se envia el formulario
            if(correct){
                $.ajax({
                    url: 'imageUpload.php',
                    data: data,
                    cache: false,
                    contentType: false,
                    processData: false,
                    method: 'POST',
                    success: function(response){
                        console.log(response);
                    }
                });

            }else{//si hay algun fichero que no sea una iamgen ,avisar
                alert("Los ficheros seleccionados deben ser imágenes");
            }
        }else{//si no contiene ficheros,avisar
            alert("Debes seleccionar almenos una imagen");
        }


    });

I think its all correct, if I append another value to formdata (not a file) ,is received on teh destination file

First thing you need to add a

multipart/form-data

in your request header, you always do that when making request with file type data.

And if you append the file data in FormData instance (which is data in your case). you use append method to append the data in FormData and use method get(key) to get the value associated with the key in FormData.

So your console.log(data) wouldn't print any file object but

console.log(data.get("file"))

will do, where file is key which you used to append file.

read this: https://developer.mozilla.org/en-US/docs/Web/API/FormData

Not sure why it is happening. Try posting the html bit as well.

Another solution for this would be having accept attribute for the input. That way it only allows files specified in the accept attribute.

<form id='uploadImgForm'>
  <!-- If uploading multiple files, the name should have an '[]' at the end, implying its an array of files -->
  <input type='file' multiple name='uploaded_files[]' accept="image/*" />

  <!-- If uploading single file use like this -->
  <input type='file' name='uploaded_files' accept="image/*" />

  <button type='submit'>Upload Files</button>
</form>

Javascript:

('#uploadImgForm').submit(function(e){
    e.preventDefault();
    var data = new FormData(this);
    $.ajax({
      url: 'imageUpload.php',
      data: data,
      cache: false,
      contentType: false,
      processData: false,
      method: 'POST',
      success: function(response){
        console.log(response);
      }
    });
});

The file(s) should appear in $_POST under uploaded_files key. Note uploaded_files will be an array if multiple files are uploaded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM