Skip to content
Advertisement

jquery ajax POST with jquery GET as formdata input

I am trying to invoke a jquery ajax POST request which has formdata as multiple files located on file server. This is my ajax request;

var formData = new FormData();
$.ajax({
        url: 'url',
        method: 'POST',
        contentType: false,
        processData: false,
        data: formData,
        beforeSend: function (xhr) {
            xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
        },
        success: function(res){
            console.log('successfully')
        },
        error: function(){
            console.log('error')
        }
    })

where formData has files located somewhere on the file server which I tried to fetch using jquery get and tried to add in formData on document ready like below;

$.get("http://localhost/file.xml",  function(data) { 
    var data1 = data;
    var file = new File([data1], "file.xml");
    formData.append('file', file);
});

Is it possible to pass or create formData having files located on the file server in ajax POST request?

Advertisement

Answer

You would need to convert it to a blob

$.ajax({
  url: "http://localhost/file.xml",
  method: "GET",
  dataType: "text"
}).done(function( content ) {
  var blob = new Blob([content], { type: "text/xml" });
  formData.append("file", blob);
});
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement