I have this JS code (given below) which converts a JSON file to XML file. Everything works perfectly (I get the contents of the file), but now I want to fetch the filename of the uploaded file.
function onChange(event) {
var reader = new FileReader();
reader.onload = (event)=>{
let data = JSON.parse(event.target.result);
$("#jsonArea").val(event.target.result);
var finalXML = '<root>' + x2js.json2xml_str($.parseJSON(event.target.result)) + '</root>';
var finalName = event.target.files[0].name; //setting it here
$("#xmlArea").val(finalXML);
finalXML = finalXML.split('FORM3CA').join('FORM3CB');
finalXML = finalXML.split('F3CA').join('F3CB');
finalXML = finalXML.split('<CreationInfo>')[0] + '<CreationInfo><SWVersionNo>1.0</SWVersionNo><SWCreatedBy>SW20000</SWCreatedBy><JSONCreatedBy>SW20000</JSONCreatedBy><JSONCreationDate>2021-11-21</JSONCreationDate><IntermediaryCity>311</IntermediaryCity></CreationInfo>' + finalXML.split('</CreationInfo>')[1]
finalXML = finalXML.split('I_We1').join('I_We');
console.log(finalName); //here
}
reader.readAsText(event.target.files[0]);
}
document.getElementById('file').addEventListener('change', onChange);
I was suggested to use event.target.files[0].name
in order to get the filename of the uploaded file (by @HeryKurniawan in comments of this post). But, when I try to console.log()
the finalName
variable (as you can see in above code), it shows me this error –
What is wrong in my code? I have also tried using event.target.file.name
& event.target.file[0].name
, but that doesn’t work either. Kindly guide… Thanks! 🙂