簡體   English   中英

blob.slice()導致一個空的blob-javascript

[英]blob.slice() results in an empty blob - javascript

我正在嘗試將大文件發送到服務器,所以我正在使用分塊技術以便以可靠的方式進行操作。

    private readonly sendChunk = (file: File, progressModel: ProgressResponseModel): void => {
        const offset = progressModel.Offset;
        if (offset > file.size)
            throw new Error("Offset cannot be greater than the file size");

        const expectedSize = progressModel.ExpectedChunkSize;

        const blobChunk = file.slice(offset, expectedSize);

        const xhr = new XMLHttpRequest();
        xhr.onload = (ev: Event): void => {
             if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
                    const progress = this.progressFromText(xhr.responseText);

                    if (progress.Offset >= 0) {
                        this.sendChunk(file, progress);
                    }

                    console.log(`${progress.Progress} %`);
                }
            }

        xhr.open("POST", this._uploadChunkUrl, true);
        xhr.send(blobChunk);
    }

服務器發回從何處開始新塊,以及應從多大塊開始。 如您所見,以上功能以遞歸方式執行。

但是,如果文件需要發送多個塊,則第二次調用const blobChunk = file.slice(offset, expectedSize); 我得到一個空塊(長度為0)。

我可以保證file arg始終有效(當console.log ed時)。

我已經看到了這個問題 ,但是我確定我的文件沒有被刪除或重命名。 我也看到了這個問題 對於Chrome和Firefox(最新版本),以及Edge,我都得到相同的行為。

謝謝!

更新好的,所以我做了一個虛擬方法來隔離此問題:

    readonly chunkIt = (file: Blob): void => {
        var offset = 0;
        var length = 512 * 1024;

        while (offset >= 0) {
            const blobChunk = file.slice(offset, length);
            console.log(blobChunk);

            offset += length;
            if (offset > file.size) offset = -1;
        }
    }

並使用它:

   $("input[name='fileUpload']").on("change", (e) => {
        const files = e.target.files;
        if (typeof files === "undefined" || files === null || files.length === 0)
            e.preventDefault();

        const file = files[0];

        this._client.chunkIt(file);
    });

僅第一次記錄正確的Blob ,以下均為空。

解決了

從這個問題開始- 使用Java腳本將文件拆分為塊,結果是我忘了抵消end索引了。

您需要使用splice()而不是slice()

更換

const blobChunk = file.slice(offset, expectedSize);

const blobChunk = file.splice(offset, expectedSize);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM