Splitting a File into Chunks with Javascript

旧街凉风 提交于 2019-11-28 00:42:26

问题


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++;
  }

回答1:


Was slicing off the wrong ends:

console.log(file.slice(offset,chunkSize));

should have been

console.log(file.slice(offset,offset+chunkSize));


来源:https://stackoverflow.com/questions/32898082/splitting-a-file-into-chunks-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!