Skip to content Skip to sidebar Skip to footer

Cannot Upload File Using Ajax

I have cgi for upload files, when I use the
to upload files, it works great, but it doesn't work if I use ajax to send data...... The form is like this:

I check the api of the upload, and found that I need to send the name of the button, too!

So the ajax is now:

var upfile=document.getElementById("upfile");
            var upform=document.getElementById("upform");
            var btnUpload=document.getElementById("btnUpload");
            var info=document.getElementById("InfoText");
            var xhr;

            upform.onsubmit = function(event){
                event.preventDefault();

                info.innerHTML="";

                var files=upfile.files;
                var formData=newFormData();
                if(files[0].name.split(".")[1]!="bin"){
                    info.innerHTML="The file should be .bin file.";
                }else{
                    info.innerHTML="Uploading, please wait.";
                    formData.append("file",files[0],files[0].name);
                    formData.append("send","Send");

                    if (window.XMLHttpRequest) {
                        xhr=newXMLHttpRequest();
                    }else{
                        xhr=newActiveXObject("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();
                    }
                }
            }

            functiononReceive(){
                var xml;
                var elem;
                if(xhr.readyState==4){
                    if(xhr.status==200){
                        xml=xhr.responseText;
                        info.innerHTML="Uploaded:"+xml;
                    }else{
                        info.innerHTML="Something is error.";
                    }
                }
            }

I'm so foolish~ Who knows that the name of button is important when I upload a file?

And thanks to all for giving me any advices!

Post a Comment for "Cannot Upload File Using Ajax"