2

I have the following code for, uploading the file using ajax because I don't want to use form action . But I unable to do so. The code is :

Select xml file to upload:
<input type="file" name="fileToUpload" id="uploadFile">
<input type="submit" id="upload_xml" value="Upload Xml">

The ajax code is:

$('#upload_xml').on('click', function() {

var file_data = $('#uploadFile').prop('files')[0];      
var form_data = new FormData();
console.log('hi'+file_data); // this gives [object File]
form_data.append('file', file_data);
console.log('yoyo'+form_data);  // this gives  [object FormData]              
$.ajax({
    url: 'upload.php',
    dataType: 'text',  
    cache: false,
    contentType: false,
    processData: false,
    data: form_data,                         
    type: 'post',
    success: function(response){
        alert(response); 
    }
 });

});

I saw many discussions on various threads, but none work for me. I have done this before without any error, I don't know what is the error :( where I am wrong here. Is there any js file that I need to include??

Ara
  • 145
  • 2
  • 10
  • Possible duplicate of [Reading file contents on the client-side in javascript in various browsers](https://stackoverflow.com/questions/750032/reading-file-contents-on-the-client-side-in-javascript-in-various-browsers) – Melchia Mar 10 '18 at 19:31

2 Answers2

0

You need to replace + with , You need also to read the file first & extract its content

  var file = $('#uploadFile').prop('files')[0];
    var file_data = '';
if (file) {
    var reader = new FileReader();
    reader.readAsText(file, "UTF-8");
    reader.onload = function (evt) {
        file_data = evt.target.result;
    }
    reader.onerror = function (evt) {
        file_data = "error reading file";
    }
}
    var form_data = new FormData();
    console.log('hi',file_data);
    form_data.append('file', file_data);
    console.log('yoyo',form_data.get('file')); 
Melchia
  • 22,578
  • 22
  • 103
  • 117
  • @Ara does this solve your problem? otherwise I'm obliged to delete my answer – Melchia Mar 10 '18 at 19:09
  • I did , but I get FromData{} on console. It shouldn't be empty right?? and only hi and yoyo are alerted, why is this so?? Can u help please – Ara Mar 10 '18 at 19:12
  • @Ara can you check again please? – Melchia Mar 10 '18 at 19:23
  • It logs hi C:\fakepath\ER_diagram.xml and yoyo C:\fakepath\ER_diagram.xml – Ara Mar 10 '18 at 19:32
  • unexpected identifier on var file = $('#uploadFile')document.getElementById("fileToUpload").files[0]; This is not correct, fileToUpload is name not id. And I beleive $('#uploadFile') does same work as getElementById('uploadFile'). why to write twice? – Ara Mar 10 '18 at 19:49
0

Use below mentioned code:

 for (var pair of formData.entries()) {
        console.log(pair[0] + ", " + pair[1]);
      }
Ajay
  • 917
  • 3
  • 12
  • 26