使用Javascript将文件拆分为块 [英] Splitting a File into Chunks with Javascript
本文介绍了使用Javascript将文件拆分为块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试获取单个文件对象,并按指定的块大小将其拆分为块。
在我的示例中,尝试将单个文件拆分为1MB块。所以我想出它需要多少块,然后我试图从'offset'开始切片文件(当前块我在*块大小上),并切掉一个块大小。
我的第一个切片正确地以1MB出现,但随后的切片变成0,任何想法为什么?
这里有一个有效的代码:
I'm trying to take a single file object and split it into chunks by a specified chunk size. In my example, trying to split a single file into 1MB chunks. So I figure out how many chunks it would take, then I'm trying to slice the file starting from the 'offset' (current chunk I'm on * chunk size), and slicing off a chunk size. My first slice comes out properly at 1MB but my subsequent slices turn out to 0, any ideas why? Have a working codepen here:
http://codepen.io/ngalluzzo/pen/VvpYKz?editors=001 [1]
var file = $('#uploadFile')[0].files[0];
var chunkSize = 1024 * 1024;
var fileSize = file.size;
var chunks = Math.ceil(file.size/chunkSize,chunkSize);
var chunk = 0;
console.log('file size..',fileSize);
console.log('chunks...',chunks);
while (chunk <= chunks) {
var offset = chunk*chunkSize;
console.log('current chunk..', chunk);
console.log('offset...', chunk*chunkSize);
console.log('file blob from offset...', offset)
console.log(file.slice(offset,chunkSize));
chunk++;
}
推荐答案
正在切断错误的目的:
console.log(file.slice(offset,chunkSize));
应该是
console.log(file.slice(offset,offset+chunkSize));
这篇关于使用Javascript将文件拆分为块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文