HTML5多文件上传

2013-09-24 14:32  3095人阅读  评论 (0)

HTML5多文件上传

multi-file-upload.php

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    header('Content-Type: text/json');
    move_uploaded_file($_FILES['file']['tmp_name'], $_FILES['file']['name']);
    sleep(5);
    echo json_encode(array('url'=>$_FILES['file']['name']));
    exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<script>
window.addEventListener('load', function(){
    if (window.navigator.userAgent.indexOf('Chrome') == -1) {
        alert('本上传只支持谷歌浏览器!');
        return;
    }

    document.getElementById('file').addEventListener('change', function() {
        for (var i=0; i<this.files.length; i++) {
            var file = this.files[i];
            var formData = new FormData();
            formData.append("file", file);

            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'multi-file-upload.php', false);
            xhr.onload = function() {
                if (this.status == 200) {
                    var response = JSON.parse(this.responseText);
                    var img = new Image();
                    img.src = response.url;
                    document.body.appendChild(img);
                } else {
                    alert('error: '+this.status);
                }
            };
            xhr.send(formData);
        }
    });
});
</script>
</head>
<body>
    <input type="file" id="file" multiple="multiple" /><br />
</body>
</html>
豫ICP备09035262号-1