PHP - HTML5 API上传已损坏

时间:2015-04-15 07:30:24

标签: javascript php html

任何人都可以帮我处理我的代码?我想使用HTML5 API构建上传功能。如果我上传的文件少于1mb,文件就可以了。但是,如果文件超过1mb,文件将被破坏。

HTML文件:

<!DOCTYPE html>
<html>
    <head>
        <title>Upload</title>
        <script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
    </head>
    <body>
        <form method="POST" action="upload.php" enctype='multipart/form-data'>
            <input type="file" name="fileToUpload" id="file"><br />
            <input type="submit" id="submit">
        </form>
    </body>


<script>
    $(document).ready(function(){
        $('#submit').on('click', function(e){
            e.preventDefault();
            sendRequest();
        });

        //window.BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder;

        var bytes_per_chunk = 1048576; // 1mb chunk sizes.
        var global_upload_counter = 0;

        function sendRequest(){
            var blob = document.getElementById('file').files[0];
            var total_size = blob.size;

            var start = 0;
            var end = bytes_per_chunk;
            // var counter = 1;
            while(start < total_size)
            {
                // console.log('start : ' + start + ', end :' + end + ' and counter : ',  counter);
                var chunk = blob.slice(start, end);
                uploadFile(chunk, blob.name);
                start = end;
                end = start + bytes_per_chunk;
                //counter++;
            }

        }

        function uploadFile(chunk, filename){
            var fd = new FormData();
            fd.append('fileToUpload', chunk);

            var xhr = new XMLHttpRequest();

            xhr.addEventListener('load', uploadComplete, false);
            xhr.addEventListener('error', uploadFailed, false);
            xhr.addEventListener('abort', uploadCanceled, false);

            xhr.open('POST', 'upload.php?filename=' + filename);
            xhr.send(fd);

        }

        function uploadComplete(evt) {
            // This event is raised when the server send back a response 
            if (evt.target.responseText != ""){
                alert(evt.target.responseText);
            }
        }

        function uploadFailed(evt) {
            alert("There was an error attempting to upload the file.");
        }

        function uploadCanceled(evt) {
            xhr.abort();
            xhr = null;
        }
    });
    </script>
</html>

PHP代码(upload.php):

<?php

$target_path = "upload/";

$tmp_name = $_FILES['fileToUpload']['tmp_name'];
$size = $_FILES['fileToUpload']['size'];
$name = $_FILES['fileToUpload']['name'];
$filename =  $_GET['filename'];

//$target_file = $target_path.$name;

$complete = $target_path. $filename;

// append; open or create binary file for writing at end-of-file
$com = fopen($complete, "ab");
error_log($target_path);

// read as binary
$in = fopen($tmp_name, "rb");
if($in){
    while ($buff = fread($in, $size)){
        fwrite($com, $buff);
    }
}
fclose($in);

2 个答案:

答案 0 :(得分:1)

首先,为什么要将文件分成块?您可以通过AJAX上传整个文件。您遇到的错误可能是由于块逻辑。 尝试删除块逻辑,它将正常工作。所以你的上传功能看起来像这样:

$(document).ready(function(){
        $('#submit').on('click', function(e){
            e.preventDefault();
            sendRequest();
        });

        //window.BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder;

        var bytes_per_chunk = 1048576; // 1mb chunk sizes.
        var global_upload_counter = 0;

        function sendRequest(){
            var blob = document.getElementById('file').files[0];
            var total_size = blob.size;

            uploadFile(blob,filename);
        }

        function uploadFile(chunk, filename){
            var fd = new FormData();
            fd.append('fileToUpload', chunk);

            var xhr = new XMLHttpRequest();

            xhr.addEventListener('load', uploadComplete, false);
            xhr.addEventListener('error', uploadFailed, false);
            xhr.addEventListener('abort', uploadCanceled, false);

            xhr.open('POST', 'upload.php?filename=' + filename);
            xhr.send(fd);

        }

        function uploadComplete(evt) {
            // This event is raised when the server send back a response 
            if (evt.target.responseText != ""){
                alert(evt.target.responseText);
            }
        }

        function uploadFailed(evt) {
            alert("There was an error attempting to upload the file.");
        }

        function uploadCanceled(evt) {
            xhr.abort();
            xhr = null;
        }
    });

而不是块,发送完整的文件,它应该工作。 如果您担心上传进度,请参考以下几种解决方案: jQuery Upload Progress and AJAX file uploadFile upload progress bar with jQuery

答案 1 :(得分:0)

查看user470714在uploading a file in chunks using html5上提供的答案,我发现了问题。

ajax实际上没有按顺序上传块。所以我更新了我的HTML代码如下,现在它工作正常:

<!DOCTYPE html>
<html>
    <head>
        <title>Upload</title>
        <script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
    </head>
    <body>
        <form method="POST" action="upload.php" enctype='multipart/form-data'>
            <input type="file" name="fileToUpload" id="file"><br />
            <input type="submit" id="submit">
        </form>
    </body>

<script>
    $(document).ready(function(){
        $('#submit').on('click', function(e){
            e.preventDefault();
            sendRequest();
        });

        //window.BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder;

        var bytes_per_chunk = 1048576; // 1mb chunk sizes.
        var global_upload_counter = 0;


        function sendRequest(){
            var blob = document.getElementById('file').files[0];

            var total_size = blob.size;

            window.upload_counter  = 0;
            window.upload_filearray = [];


            var start = 0;
            var end = bytes_per_chunk;
            while(start < total_size)
            {
                var chunk = blob.slice(start, end);

                window.upload_filearray[window.upload_counter] = chunk;
                window.upload_counter++;

                start = end;
                end = start + bytes_per_chunk;

            }

            // initiate upload the first time
            window.upload_counter = 0;
            window.filename = blob.name;
            uploadFile(window.upload_filearray[window.upload_counter]);

        }


        function uploadFile(chunk){
            var fd = new FormData();
            fd.append('fileToUpload', chunk);

            var xhr = new XMLHttpRequest();

            xhr.addEventListener('load', uploadComplete, false);
            xhr.addEventListener('error', uploadFailed, false);
            xhr.addEventListener('abort', uploadCanceled, false);

            xhr.open('POST', 'upload.php?filename=' + window.filename);

            window.upload_counter++;

            xhr.send(fd);

        }

        function uploadComplete(evt) {
            // This event is raised when the server send back a response 
            if (evt.target.responseText != ""){
                console.log(evt.target.responseText);
            }

            if(window.upload_filearray.length > window.upload_counter){
                uploadFile(window.upload_filearray[window.upload_counter]);
            }
        }

        function uploadFailed(evt) {
            alert("There was an error attempting to upload the file.");
        }

        function uploadCanceled(evt) {
            xhr.abort();
            xhr = null;
        }


    });
    </script>
</html>