Ajax 文件上传仅在 Opera 工作


Ajax file upload working only at Opera

我尝试使用Ajax上传照片,编写的代码在Opera(我的标准浏览器)中没有问题。现在我已经在其他浏览器中对其进行了测试,它们都返回了错误。我的 PHP 脚本以

if(!empty($_FILES)) {
    //todo
} else {
    exit();
}

所以我试着把var_dump($_FILES); die();放在开头,看看出了什么问题。他们都把这个还给了array(0) {}.我已经在FireFox,Chrome,Safari(所有最新版本),win7上的IE9和Debian上的最新Firefox上进行了测试。最大的问题,我不明白为什么它不起作用,因为在开发人员工具和上面的所有浏览器中,我可以在正确的位置看到具有正确名称的文件。

这是我要上传的JS:

var photo_input1 = document.createElement('input');
photo_input1.setAttribute('type','file');
photo_input1.setAttribute('class','photo_input');
photo_input1.setAttribute('id','photo1');
photo_input1.addEventListener('change', function() {
    upload_photo(this.id,this.files[0])
});
var upload_photo = function(filename,file) {
    var data_arr = Array();
    data_arr['callback_name'] = 'upload_photo';
    upload_file(filename,file,'add_photo.php',data_arr);
}
var upload_file = function(filename,file,url,data_arr) {
    var datapack = null;
    var ajaxanswer = function() {
        try {
            if (ajax.readyState == 4) {
                if (ajax.status == 200) {
                    //todo
                } else {
                    alert('Problems:' + "'n" + ajax.statusText);
                }
            }
        } catch(e) {
        }
    }
    try {
        var ajax = new XMLHttpRequest();
    } catch(e) {
        try {
            var ajax = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            try {
                var ajax = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                return false;
            }
        }
    }
    if(ajax) {
        if(typeof url != 'undefined') {
            datapack = new FormData;
            datapack.append(filename,file);
            if(typeof data_arr != 'undefined') {
                for(key in data_arr) {
                    datapack.append(key, data_arr[key]);
                }
            }
            ajax.open('POST',url, true);
            ajax.setRequestHeader('Content-type', 'multipart/form-data');
            ajax.onreadystatechange = ajaxanswer;
            ajax.send(datapack);
        }
    }
}

无法使用 ajax 上传文件。通常的做法是使用 iframe 内部并使用 iframe 提交表单。您可以在此处阅读其中一种方法。

你也可以阅读这个答案。

使用 XHR2,支持通过 AJAX 上传文件。 例如,通过 FormData 对象,但不幸的是,所有/旧浏览器都不支持它

FormData 只能在 Opera v12 及更高版本中与其他相对较新的浏览器一样工作:http://caniuse.com/#search=FormData

您可以尝试这样做来上传类似Ajax的文件:https://github.com/valums/file-uploader。正如 Arun P Johny 所提到的,Ajax 没有上传,但您可以使用一些解决方法,例如在这种情况下隐藏 iframe。