How to upload a file with ajax in small chunks and check for fails, re-upload the parts that failed.

前端 未结 2 2014
旧时难觅i
旧时难觅i 2021-02-03 15:31

I have a file uploaded by a user, and I\'d like to achieve the following.

  1. Divide the file into smaller chunks about a megabyte.
  2. Upload each chunk, and wai
2条回答
  •  时光取名叫无心
    2021-02-03 15:37

    I've modified afzalex's answer to use readAsArrayBuffer(), and upload the chunk as a file.

        var loaded = 0;
        var reader = new FileReader();
        var blob = file.slice(loaded, max_chunk_size);
        reader.readAsArrayBuffer(blob);
        reader.onload = function(e) {
          var fd = new FormData();
          fd.append('filedata', new File([reader.result], 'filechunk'));
          fd.append('loaded', loaded);
          $.ajax(url, {
            type: "POST",
            contentType: false,
            data: fd,
            processData: false
          }).done(function(r) {
            loaded += max_chunk_size;
            if (loaded < file.size) {
              blob = file.slice(loaded, loaded + max_chunk_size);
              reader.readAsArrayBuffer(blob);
            }
          });
        };
    

提交回复
热议问题