Tags
Asked 2 years ago
22 Jul 2021
Views 218
Fatima

Fatima posted

How to use FormData for AJAX file upload?

Ajax file upload with FormData , how to do it ? i tried simple ajax code not working as per need to upload file

chirag

chirag
answered Jul 24 '21 00:00

HTML ::


<form id='anyid'  method="post" enctype="multipart/form-data" >
<input type='file' name='image' /> 
</form>

JAVASCRIPT (JQUERY):

$("form#anyid").submit(function(e) {
    e.preventDefault();    
    var formData = new FormData(this);
    $.ajax({
        url: 'https://anydomain.com/fileupload',
        type: 'POST',
        data: formData,
        success: function (data) {
                console.log('we are done with upload');
        },
        cache: false,
        contentType: false,
        processData: false
    });
});


here main part is
var formData = new FormData(this);
new FormData will create object with all form field of passed form element.

even you can append the file as need like this
formData.append(name, blob, fileName)


One can use any server-side code to file get uploaded at server

Post Answer