Ajax上传文件无效

Html code :

<input type="file" id="file" />

jQuery code :

$.ajax({
        url: 'go.php',
        data: {file:$('#file').attr('files'),upload:name},
        cache: false,
        contentType: 'multipart/form-data',
        processData: false,
        type: 'POST',
        success: function(data){
            alert(data);
        },
        error: function(data){
            alert("error");
        }
    });

PHP code :

if(isset($_POST['file'])){
    echo "1";
}

After upload alert empty message !

But this code should error "1"

Uploading files direcley using ajax is not possible. but there are some workarounds using frames. try this tutorial:

http://net.tutsplus.com/tutorials/javascript-ajax/uploading-files-with-ajax/

Read this post cfr: jQuery Ajax File Upload

Its a workaround but might help...

function uploadFile() {
            var file = document.getElementById('fileToUpload').files[0];
                if (file) {
                    var fileSize = 0;
                    var fileType = ''+file.type;
                    if(checkType(fileType)){
                            var fd = new FormData();
                            fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
                            var xhr = new XMLHttpRequest();

                            xhr.open("POST", "uploadPhoto");
                            xhr.send(fd);
                    }
                    else{
                            document.getElementById('fileToUpload').value ='' ;
                            alert("Choose of specified file Format only.");
                        }
                }
        }*

Always remember if any of these solutions dont work and files attributes are not showing on:

$.ajax({ url : here });

despite everything being correct.

If your <form> itself is getting loaded from ajax call,

  1. try putting it in main file(ie. one being in url) or
  2. Put <form> file at location appearing in url (ie. final folder of file appearing in url) and then use include() function to include file.