使用html5以块的形式上传文件

时间:2011-10-21 18:06:26

标签: php file html5 upload

我正在尝试使用html5的File API以块的形式上传文件,然后在php中在服务器端重新组装它。我正在上传视频,但是当我合并服务器端的文件时,大小已经增加,并且它正在变为无效文件。请注意,以下html5代码仅适用于浏览器chrome。在Chrome 9中测试,因为它使用文件API的切片功能。 有人可以指导我吗? 谢谢

PHP源

<?php

$target_path = "uploads/";
$tmp_name = $_FILES['fileToUpload']['tmp_name'];
$size = $_FILES['fileToUpload']['size'];
$name = $_FILES['fileToUpload']['name'];


$target_file = $target_path . basename($name);


$complete = "complete.mov";
$com = fopen("uploads/".$complete, "ab");
error_log($target_path);

// Open temp file
$out = fopen($target_file, "wb");

if ( $out ) {
    // Read binary input stream and append it to temp file
    $in = fopen($tmp_name, "rb");
    if ( $in ) {
        while ( $buff = fread( $in, 1048576 ) ) {
            fwrite($out, $buff);
            fwrite($com, $buff);
        }   
    }
    fclose($in);
    fclose($out);
}
fclose($com);

?>

HTML源

<!DOCTYPE html>
<html>
    <head>
        <title>Upload Files using XMLHttpRequest</title>
        <script type="text/javascript">

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

            function sendRequest() {
                var blob = document.getElementById('fileToUpload').files[0];
                const BYTES_PER_CHUNK = 1048576; // 1MB chunk sizes.
                const SIZE = blob.size;
                var start = 0;
                var end = BYTES_PER_CHUNK;
                while( start < SIZE ) {
                    var chunk = blob.slice(start, end);
                    uploadFile(chunk);
                    start = end;
                    end = start + BYTES_PER_CHUNK;
                }
            }

            function fileSelected() {
                var file = document.getElementById('fileToUpload').files[0];
                if (file) {
                    var fileSize = 0;
                    if (file.size > 1024 * 1024)
                        fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
                    else
                        fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';

                    document.getElementById('fileName').innerHTML = 'Name: ' + file.name;
                    document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
                    document.getElementById('fileType').innerHTML = 'Type: ' + file.type;
                }
            }

            function uploadFile(blobFile) {
                //var file = document.getElementById('fileToUpload').files[0];  
                var fd = new FormData();
                fd.append("fileToUpload", blobFile);

                var xhr = new XMLHttpRequest();
                xhr.upload.addEventListener("progress", uploadProgress, false);
                xhr.addEventListener("load", uploadComplete, false);
                xhr.addEventListener("error", uploadFailed, false);
                xhr.addEventListener("abort", uploadCanceled, false);
                xhr.open("POST", "upload.php");
                xhr.onload = function(e) {
                  alert("loaded!");
                  };

                xhr.send(fd);
                //alert("oen over");
            }

            function uploadProgress(evt) {
                if (evt.lengthComputable) {
                    var percentComplete = Math.round(evt.loaded * 100 / evt.total);
                    document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
                }
                else {
                    document.getElementById('progressNumber').innerHTML = 'unable to compute';
                }
            }

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

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

            function uploadCanceled(evt) {
                xhr.abort();
                xhr = null;
                //alert("The upload has been canceled by the user or the browser dropped the connection.");
            }
        </script>
    </head>
    <body>
        <form id="form1" enctype="multipart/form-data" method="post" action="upload.php">
            <div class="row">
                <label for="fileToUpload">Select a File to Upload</label><br />
                <input type="file" name="fileToUpload" id="fileToUpload" onchange="fileSelected();"/>
                <input type="button" value="cancel"  onClick="uploadCanceled();"/>
            </div>
            <div id="fileName"></div>
            <div id="fileSize"></div>
            <div id="fileType"></div>
            <div class="row">
                <input type="button" onclick="sendRequest();" value="Upload" />
            </div>
            <div id="progressNumber"></div>
        </form>
    </body>
</html>

5 个答案:

答案 0 :(得分:13)

我试图解决这个问题并找到了以下内容,希望对您有用:

1)不推荐使用用于切片文件的JS函数。我正在运行Chrome v14,控制台无法识别它。在我做任何事情之前,我必须将其更改为:

var chunk = blob.webkitSlice(start, end);

2)我尝试了更小的文件(大约10MB),但遇到了类似的问题 - 上传后我的视频总是被破坏了。当我比较原文和'副本'时,我注意到一件特别的事情:文件的各个部分似乎只是混淆了 - 它就在那里,但顺序错误。

我怀疑您当前程序遇到的一个问题是没有采取措施确保文件以正确的顺序组装。我相信正在发生的事情是你的JS多次运行uploadFile,而不是等待先前的上传完成,服务器尝试按接收顺序组装文件,但这与文件发送的顺序不一样

我能够通过让你的代码工作(稍微修改,作为概念证明一起被黑客攻击),通过为每个文件分配一个接收到的序列号,然后在收到所有部件后组装它们来证明这一点。为了。完成后,我可以在上传后播放我的视频文件。

我认为你将不得不采取类似措施。接收所有文件块,然后组装它们,或者至少确保您采取必要的措施按顺序组装它们。我不确定为什么你的文件会变大(我确实在早期观察到这种现象),所以我怀疑它只是一些奇怪的副作用,否则就不会同步文件块。

您将立即遇到的一个难点是Javasacript中的Blob对象不支持更改或设置文件名,因此您无法在客户端为该文件提供唯一的标识符。我做了什么,作为一个简单的解决方法如下:

            var i = 1;
            while( start < SIZE ) {
                var chunk = blob.webkitSlice(start, end);
                uploadFile(chunk, i);
                i++;

                start = end;
                end = start + BYTES_PER_CHUNK;
            }


function uploadFile(blobFile, part) {
     ....
     xhr.open("POST", "test.php?num=" + part);
     ....
}

正如您可能在服务器端猜测的那样,我只是使用该GET变量来分配标识符,并将其用作需要在服务器上完成的任何其他处理的基础。

无论如何,这并没有直接解决文件大小增长的问题,所以我只希望这会对你有所帮助;我很想知道你还能找到什么!

答案 1 :(得分:7)

你好我已经检查过你的php文件了。我添加了一些sequirity代码。并更改了文件名attribut并删除了dubbel文件创建。在这里。

<?php
session_start();
if ($_SESSION['newsession'] == false and $_SESSION['TypeUser'] == 'Admin' ){
$target_path = "../uploads/";
$tmp_name = $_FILES['fileToUpload']['tmp_name'];
$size = $_FILES['fileToUpload']['size'];
$name = $_FILES['fileToUpload']['name'];
$name2 = $_GET['filename'];

$target_file = $target_path.$name;


$complete =$target_path.$name2;
$com = fopen($complete, "ab");
error_log($target_path);

// Open temp file
//$out = fopen($target_file, "wb");

//if ( $out ) {
    // Read binary input stream and append it to temp file
    $in = fopen($tmp_name, "rb");
    if ( $in ) {
        while ( $buff = fread( $in, 1048576 ) ) {
           // fwrite($out, $buff);
            fwrite($com, $buff);
        }   
    }
    fclose($in);

//}
//fclose($out);
fclose($com);
}else{
    echo'you are not logged in.';
}
?>

对于html部分,我改变了上传多部分文件的方式。我将主题放入列表中并逐个上传。这是代码。

<script type="text/javascript" > 
function uploadchange() {
            var input = document.getElementById("file");
            var ul = document.getElementById("uploadlist");
            while (ul.hasChildNodes()) {
                ul.removeChild(ul.firstChild);
            }
            for (var i = 0; i < input.files.length; i++) {
                var li = document.createElement("li");
                thefilesize = input.files[i].fileSize||input.files[i].size;
                if (thefilesize > 1024 * 1024){
                             thefilesize = (Math.round(thefilesize  * 100 / (1024 * 1024)) / 100).toString() + 'MB';
                         }else{
                                thefilesize = (Math.round(thefilesize  * 100 / 1024) / 100).toString() + 'KB';
                }

                li.innerHTML = input.files[i].name + " " + thefilesize ;
                ul.appendChild(li);             
            }
            if(!ul.hasChildNodes()) {
                var li = document.createElement("li");
                li.innerHTML = 'No Files Selected';
                ul.appendChild(li);
            }
            sendRequest();
        }

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

            function sendRequest() {
        var blob = document.getElementById('file').files[0];
                var BYTES_PER_CHUNK = 1048576; // 1MB chunk sizes.
                var SIZE = blob.size;
                var start = 0;
                var end = BYTES_PER_CHUNK;
        window.uploadcounter=0;
        window.uploadfilearray = [];
        document.getElementById('progressNumber').innerHTML = "Upload: 0 % ";
                while( start < SIZE ) {

                    var chunk = blob.slice(start, end);
            window.uploadfilearray[window.uploadcounter]=chunk;
                        window.uploadcounter=window.uploadcounter+1;
                    start = end;
                    end = start + BYTES_PER_CHUNK;
                }
        window.uploadcounter=0;
        uploadFile(window.uploadfilearray[window.uploadcounter],document.getElementById('file').files[0].name);
            }

            function fileSelected() {
                var file = document.getElementById('fileToUpload').files[0];
                if (file) {
                    var fileSize = 0;
                    if (file.size > 1024 * 1024)
                        fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
                    else
                        fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';

                    document.getElementById('fileName').innerHTML = 'Name: ' + file.name;
                    document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
                    document.getElementById('fileType').innerHTML = 'Type: ' + file.type;
                }
            }

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

                var xhr = new XMLHttpRequest();


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

                xhr.open("POST", "./system/upload2.php?filename="+filename);

                xhr.onload = function(e) {
            window.uploadcounter=window.uploadcounter+1;
            if (window.uploadfilearray.length > window.uploadcounter ){
                uploadFile(window.uploadfilearray[window.uploadcounter],document.getElementById('file').files[0].name); 
                var percentloaded2 = parseInt((window.uploadcounter/window.uploadfilearray.length)*100);
                document.getElementById('progressNumber').innerHTML = 'Upload: '+percentloaded2+' % ';                              
            }else{
                document.getElementById('progressNumber').innerHTML = "File uploaded";
                loadXMLDoc('./system/loaddir.php?url='+ window.currentuploaddir);

            }
                  };

                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;
                //alert("The upload has been canceled by the user or the browser dropped the connection.");
            }


</script>
<LINK HREF="./system/link.css" REL="stylesheet" TYPE="text/css">

</head>
<body>
<div id="fileselector">
<div id="containerback">

</div>
<div id="dirlijst">

</div>


<div id="container">
    <h1>Upload file</h1>
    <br />
    <form name="form1" onSubmit="return uploadFile();" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">

<div id="progressNumber"></div>


<input type="file" id="file" multiple name="uploads[]" style="visibility:hidden" onChange="uploadchange();">
<a href="#" onClick="document.getElementById('file').click();return false"><img src="system/iconfilemanager/upload.png" alt="upload file"></a>
 <div id="uploadlist">

</div>

 </form>
</div>

答案 2 :(得分:5)

更新回答

在chrome中==&gt; Slice Function接受第二个参数作为长度。

在FF ==&gt; Slice Function接受第二个参数作为结束。

代码示例

fileorblob.slice(startingPosition, length) //for chrome
fileorblob.slice(startingPosition, end)//for FF
不推荐使用

webkitslice and mozslice使用原生"slice()"

BlobBuilder也弃用Blob constructor

资源:

http://updates.html5rocks.com/2012/06/Don-t-Build-Blobs-Construct-Them

https://developer.mozilla.org/en-US/docs/Web/API/Blob

Reading files as chunks and uploading

答案 3 :(得分:3)

Slice Function接受第二个参数作为长度。其中mozSlice接受第二个参数作为结束

答案 4 :(得分:-3)

根据PHP文档,fread采用字节长度,而不是位。您尝试使用1000000而不是1048576吗?