Skip to content

Commit e242246

Browse files
authored
Create UploadLargeFile.js
1 parent b4b2007 commit e242246

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

UploadLargeFile.js

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/* Author : Suvabrata Roy
2+
Email : [email protected] */
3+
4+
function UploadLargeFile(file, callback, PostURL) {
5+
var fileSize = file.size;
6+
var chunkSize = 1 * 1024 * 1024; // bytes
7+
var offset = 0;
8+
var BOF = 0;
9+
var self = this; // reference purpose
10+
var FileReadInBlocks = null;
11+
12+
var readEventHandler = function(evt) {
13+
if (evt.target.error == null) {
14+
offset += evt.target.result.length;
15+
callback(evt.target.result, BOF, function() {
16+
if (offset >= fileSize) {
17+
console.log("Done reading file");
18+
//console.log(new Date());
19+
return;
20+
}
21+
FileReadInBlocks(offset, chunkSize, file)
22+
}, PostURL);
23+
24+
BOF = offset;
25+
} else {
26+
console.log("Read error: " + evt.target.error);
27+
return;
28+
}
29+
30+
if (offset >= fileSize) {
31+
console.log("Done reading file");
32+
//console.log(new Date());
33+
return;
34+
}
35+
}
36+
37+
FileReadInBlocks = function(_offset, length, _file) {
38+
var r = new FileReader();
39+
var blob = _file.slice(_offset, length + _offset);
40+
console.log(_offset);
41+
r.onload = readEventHandler;
42+
r.readAsDataURL(blob);
43+
}
44+
// now let's start the read with the first block
45+
FileReadInBlocks(offset, chunkSize, file);
46+
}
47+
48+
49+
function AsyncUpload(data, fileposition, seekNext, PostURL) {
50+
var xhttp = new XMLHttpRequest();
51+
xhttp.onreadystatechange = function() {
52+
if (this.readyState == 4 && this.status == 200) {
53+
seekNext();
54+
}
55+
};
56+
57+
xhttp.open("POST", PostURL, true);
58+
xhttp.setRequestHeader("Content-type", "application/json; charset=utf-8");
59+
xhttp.send(JSON.stringify({
60+
Data: data,
61+
OffSet: fileposition
62+
}));
63+
64+
}
65+
66+
67+
//Usage
68+
/*
69+
function UploadFileOnSubmit() {
70+
var file = document.getElementById("FileInput").files[0]
71+
UploadLargeFile(file, AsyncUpload, "URL To Post The data");
72+
} */

0 commit comments

Comments
 (0)