I have encountered an issue with my CGI for uploading files. It works perfectly fine when using the <form>
tag to upload files, but seems to fail when attempting to send data via ajax...
The form code looks like this:
<form id="confUpdate" enctype="multipart/form-data" method="post" action="upload.cgi">
<input id='upLoad' type='file' name="file">
<input id='btnUpload' type="submit" name="send" value="Upload">
</form>
It functions properly if I just leave the button type as 'submit'.
However, when I change the button type from 'submit' to 'button' and try to handle it with JavaScript:
window.onload=function(){
var upfile=document.getElementById("upLoad");
var upform=document.getElementById("confUpdate");
var btnUpload=document.getElementById("btnUpload");
var info=document.getElementById("InfoText");
var xhr;
btnUpload.onclick=function(){
var file=upfile.files;
var formData=new FormData();
if(file[0].name.split(".")[1]!="bin"){
info.innerHTML="The file should be a .bin file.";
}else{
info.innerHTML="";
formData.append("file",file[0],file[0].name);
}
if (window.XMLHttpRequest) {
xhr=new XMLHttpRequest();
}else{
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
try{
xhr.open('POST', 'upload.cgi', true);
xhr.setRequestHeader("content-type","multipart/form-data");
xhr.onreadystatechange = onReceive;
xhr.send(formData);
}catch(e){
xhr.abort();
}
}
function onReceive(){
var xml;
var elem;
if(xhr.readyState==4){
if(xhr.status==200){
xml=xhr.responseText;
info.innerHTML="Uploaded:" + xml;
}else{
info.innerHTML="There was an error.";
}
}
}
}
Upon clicking the button, the debug text simply displays 'Uploaded:', indicating that the file data is being sent, but the XML response from the server side remains empty.
I'm unsure whether the issue lies with my server-side code or my JavaScript implementation?
My guess is that the file should be named 'file'.
Any guidance or suggestions would be highly appreciated!