reader.onloadend未被触发

时间:2014-11-11 08:20:43

标签: javascript azure-storage

当我为多个文件运行以下代码将它们上传到Blob存储时,reader.onloadend永远不会被触发。我正在关注http://gauravmantri.com/2013/02/16/uploading-large-files-in-windows-azure-blob-storage-using-shared-access-signature-html-and-javascript/

         <!DOCTYPE html>
          <html xmlns="http://www.w3.org/1999/xhtml">
            <head>
            <title>File Uploader</title>
     <script src="js/jquery-2.0.3.min.js"></script>
     <script>
        $(document).ready(function () {

    var maxBlockSize = 256 * 1024;//Each file will be split in 256 KB.
    var numberOfBlocks = 1;
    var selectedFile = null;
    var currentFilePointer = 0;
    var totalBytesRemaining = 0;
    var blockIds = new Array();
    var blockIdPrefix = "block-";
    var submitUri = null;
    var bytesUploaded = 0;

       $("#output").hide();
       document.getElementById('file').addEventListener('change', handleFileSelect, false);

        if (window.File && window.FileReader && window.FileList && window.Blob) {
            // Great success! All the File APIs are supported.
        } else {
            alert('The File APIs are not fully supported in this browser.');
        }
         $("#uploadmetadata").click( function(){
                createPackage()
         });
        }); 
        function createPackage(){
        var jsonObject = $("#packagedata").val();   
                $('#success').hide();
                $('#files').hide();                 
                var jqXHR = $.ajax({ 
                            type: "POST",
                            url: "some url here",
                            data: JSON.stringify(jQuery.parseJSON(jsonObject)),
                            async: false,
                            contentType: "application/json",
                            success: function(data) { 
                                $('#success').show();
                                $('#files').show();

                                 return data.id;
                            },
                            error: function (req) {
                            console.log(req);
                            }
                    }); 
                    console.log(jqXHR.responseJSON.id);
                    var packagefiles = jqXHR.responseJSON.softwarePackage.softwarePackageFiles;
                                $.each(packagefiles, function (i, ob) {
                                        $('#myTable tbody').append('<tr><td><span id="fileName"></span></td><td><span id="fileSize"></span> bytes.</td><td><span id="fileType"></span></td><td></td></tr>');
                                });
                    $('#packageId').val(jqXHR.responseJSON.id);
                    return jqXHR.responseJSON.id;

    }

    function getSASUrl(filename) {
        var jqXHR = $.ajax({ 
                            type: "POST",
                            url: "some url here",
                            data: JSON.stringify({"packageId":$('#packageId').val(),"fileName":filename}),
                            dataType: "json",
                            contentType: "application/json",
                            crossDomain: true,
                            async: false,
                            success: function(res, status, xhr) { 
                                return res;
                            },
                            error: function (req) {
                            console.log(req);
                            }               
                        }); 
                        console.log(jqXHR);
        return jqXHR;
    }       



    //Read the file and find out how many blocks we would need to split it.
    function handleFileSelect(evt) {

       var f = evt.target.files; 

        for (var i = 0; i < f.length; i++) { //for multiple files 
            selectedFile = f[i];
            handleFile();
        }
    }

        //Read the file and find out how many blocks we would need to split it.
    function handleFile() {
        maxBlockSize = 256 * 1024;
        currentFilePointer = 0;
        totalBytesRemaining = 0;
        $("#output").show();
        $("#fileName").text(selectedFile.name);
        $("#fileSize").text(selectedFile.size);
        $("#fileType").text(selectedFile.type);
        var fileSize = selectedFile.size;
        if (fileSize < maxBlockSize) {
            maxBlockSize = fileSize;
            console.log("max block size = " + maxBlockSize);
        }
        totalBytesRemaining = fileSize;
        if (fileSize % maxBlockSize == 0) {
            numberOfBlocks = fileSize / maxBlockSize;
        } else {
            numberOfBlocks = parseInt(fileSize / maxBlockSize, 10) + 1;
        }
        console.log("total blocks = " + numberOfBlocks);
       console.log("total blocks = " + numberOfBlocks);
        var xhr = getSASUrl(selectedFile.name); 

        var baseUrl = xhr.getResponseHeader("X-Upload-Location");   
        console.log("final SAS" + baseUrl);

        var indexOfQueryStart = baseUrl.indexOf("?");
        console.log(baseUrl.substring(0, indexOfQueryStart));
        console.log(selectedFile.name);
        console.log(baseUrl.substring(indexOfQueryStart));

        submitUri = baseUrl.substring(0, indexOfQueryStart) + baseUrl.substring(indexOfQueryStart);
        console.log("submit" + submitUri);

 }

 var reader = new FileReader();

    reader.onloadend = function (evt) {
        if (evt.target.readyState == FileReader.DONE) { // DONE == 2
            var uri = submitUri + '&comp=block&blockid=' + blockIds[blockIds.length - 1];
            var requestData = new Uint8Array(evt.target.result);
            $.ajax({
                url: uri,
                type: "PUT",
                data: requestData,
                processData: false,
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('x-ms-blob-type', 'BlockBlob');
                    xhr.setRequestHeader('Content-Length', requestData.length);
                },
                success: function (data, status) {
                    console.log(data);
                    console.log(status);
                    bytesUploaded += requestData.length;
                    var percentComplete = ((parseFloat(bytesUploaded) / parseFloat(selectedFile.size)) * 100).toFixed(2);
                    $("#fileUploadProgress").text(percentComplete + " %");
                    uploadFileInBlocks();
                },
                error: function(xhr, desc, err) {
                    console.log(desc);
                    console.log(err);
                }
            });
        }
    };



    function uploadFileInBlocks() {
        if (totalBytesRemaining > 0) {
            console.log("current file pointer = " + currentFilePointer + " bytes read = " + maxBlockSize);
            var fileContent = selectedFile.slice(currentFilePointer, currentFilePointer + maxBlockSize);
            var blockId = blockIdPrefix + pad(blockIds.length, 6);
            console.log("block id = " + blockId);
            blockIds.push(btoa(blockId));
            reader.readAsArrayBuffer(fileContent);
            currentFilePointer += maxBlockSize;
            totalBytesRemaining -= maxBlockSize;
            if (totalBytesRemaining < maxBlockSize) {
                maxBlockSize = totalBytesRemaining;
            }
        } else {
            commitBlockList();
        }
    }

    function commitBlockList() {
        var uri = submitUri + '&comp=blocklist';
        console.log(uri);
        var requestBody = '<?xml version="1.0" encoding="utf-8"?><BlockList>';
        for (var i = 0; i < blockIds.length; i++) {
            requestBody += '<Latest>' + blockIds[i] + '</Latest>';
        }
        requestBody += '</BlockList>';
        console.log(requestBody);
        $.ajax({
            url: uri,
            type: "PUT",
            data: requestBody,
            beforeSend: function (xhr) {
                xhr.setRequestHeader('x-ms-blob-content-type', selectedFile.type);
                xhr.setRequestHeader('Content-Length', requestBody.length);
            },
            success: function (data, status) {
                console.log(data);
                console.log(status);
            },
            error: function (xhr, desc, err) {
                console.log(desc);
                console.log(err);
            }
        });

    }
    function pad(number, length) {
        var str = '' + number;
        while (str.length < length) {
            str = '0' + str;
        }
        return str;
    }


            </script>
         </head>
         <body>
              <form>
              <div style="margin-left: 20px;">
                  <h1>File Uploader</h1>
                    <input id="packageId" type="hidden"/>
                        <input id="txtSAS" type="hidden"/>
                    <p>
                       <strong>Browse Package</strong>: 
            <br/>
            <span class="input-control text">
                <textarea rows="10" cols="50" id="packagedata"></textarea><br>
                <button type="button" id="uploadmetadata" class="btn btn-sm btn-primary" role="button">Create Package Metadata</button>
            </span>
        </p>
        <p>
            <strong>SAS URI</strong>: 
            <br/>
            <span class="input-control text">
                <input type="text" id="sasUrl" style="width: 50%"
                       value=""/>
            </span>
        </p>
        <p>
            <strong>File To Upload</strong>: 
            <br/>
            <span class="input-control text">
                <input type="file" id="file" name="file" style="width: 50%" multiple />

            </span>
        </p>

            <table id="myTable" class="table table-striped">
            <thead>
                <tr>
                    <th>
                        Name
                    </th>
                    <th>
                        File Size
                    </th>
                    <th>
                        File Type
                    </th>
                    <th>
                         <strong>Progress</strong>: <span id="fileUploadProgress">0.00 %</span>
                    </th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>
    <div>
    </div>
</form>

1 个答案:

答案 0 :(得分:0)

基本上,文件是在uploadFileInBlocks()函数中读取的,您没有调用该函数。要启动上传,您必须以某种方式调用此方法。如果您查看博客文章中的代码,可以点击Upload File按钮(来自博客文章)调用此方法:

<p>
    <input type="button" value="Upload File" onclick="uploadFileInBlocks()"/>
</p>