简体   繁体   中英

When submitting a multipart/form-data with ajax, file is empty

I'm with a problem when submitting a multipart/form-data with ajax.

HTML code:

<form id='form_foto' method='post' enctype='multipart/form-data'>
   <input type='hidden' id='id_noticia' name='id_noticia' value='"+id_noticia+"' />
   <input name='foto[]' type='file' multiple />
</form>

jQuery and Ajax:

          $("#form_foto").submit(function(e){

                $("#form_foto").append("<br />Aguarde...");

                var formData = new FormData(this);

                $.ajax({
                    url: "/PortalGBD/services",
                    type: "POST",
                    data: formData,
                    async: false,
                    dataType: "multipart/form-data",
                    processData: false,
                    contentType: false,
                    success: function(resposta){
                        alert(resposta);
                    }
                });
                e.preventDefault(); 
            });
            $("#form_foto").submit();
            self.close();
        }

And the request with a file input empty:

-----------------------------65942623427134 Content-Disposition: form-data; name="id_noticia"

336 -----------------------------65942623427134 Content-Disposition: form-data; name="foto[]"; filename="" Content-Type: application/octet-stream

-----------------------------65942623427134--

Please help me with this problem. Thank you.

Please change one line from your code var formData = new FormData(this); to var formData = new FormData($(this)[0]); and then check it.

When we create instance of FormData we pass form[0] instead form. It's mean actual form element, but not jQuery selector.

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