Browser getting stuck to upload large files - javascript

I am using basic javascript and trying to upload a file appx 500Mb, but my browser is getting stuck. Below is my javascript code
main.js
'use strict';
var singleUploadForm = document.querySelector('#singleUploadForm');
var singleFileUploadInput = document.querySelector('#singleFileUploadInput');
var singleFileUploadError = document.querySelector('#singleFileUploadError');
var singleFileUploadSuccess = document.querySelector('#singleFileUploadSuccess');
var multipleUploadForm = document.querySelector('#multipleUploadForm');
var multipleFileUploadInput = document.querySelector('#multipleFileUploadInput');
var multipleFileUploadError = document.querySelector('#multipleFileUploadError');
var multipleFileUploadSuccess = document.querySelector('#multipleFileUploadSuccess');
var asyncMltipleUploadForm = document.querySelector('#asyncMltipleUploadForm');
var asyncMultipleFileUploadInput = document.querySelector('#asyncMltipleUploadInput');
var asyncMultipleFileUploadError = document.querySelector('#asyncMultipleFileUploadError');
var asyncMultipleFileUploadSuccess = document.querySelector('#asyncMultipleFileUploadSuccess');
function uploadSingleFile(file) {
var formData = new FormData();
formData.append("file", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:8080/uploadFile");
xhr.onload = function() {
console.log(xhr.responseText);
// var response = JSON.parse(xhr.responseText);
if(xhr.status == 200) {
singleFileUploadError.style.display = "none";
// singleFileUploadSuccess.innerHTML = "<p>File Uploaded Successfully.</p><p>DownloadUrl : <a href='" + response.fileDownloadUri + "' target='_blank'>" + response.fileDownloadUri + "</a></p>";
singleFileUploadSuccess.style.display = "block";
} else {
singleFileUploadSuccess.style.display = "none";
singleFileUploadError.innerHTML = (response && response.message) || "Some Error Occurred";
}
}
xhr.send(formData);
}
function resolveAfter2Seconds(file) {
return new Promise(resolve => {
// setTimeout(() => {
resolve(uploadSingleFile(file));
// }, null);
} );
}
async function asynchUploadMultipleFiles(files) {
var formData = new FormData();
for(var index = 0; index < files.length; index++) {
// formData.append("files", files[index]);
var startDate = new Date();
await resolveAfter2Seconds(files[index]);
var endDate = new Date();
var diff = endDate - startDate;
asyncMultipleFileUploadSuccess.innerHTML = "time taken :::: " + diff;
asyncMultipleFileUploadSuccess.style.display = "block";
}
}
function uploadMultipleFiles(files) {
var startDate = new Date();
var formData = new FormData();
for(var index = 0; index < files.length; index++) {
formData.append("files", files[index]);
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:8080/uploadMultipleFiles");
xhr.onload = function() {
console.log(xhr.responseText);
// var response = JSON.parse(xhr.responseText);
if(xhr.status == 200) {
multipleFileUploadError.style.display = "none";
var content = "<p>All Files Uploaded Successfully</p>";
// for(var i = 0; i < response.length; i++) {
// content += "<p>DownloadUrl : <a href='" + response[i].fileDownloadUri + "' target='_blank'>" + response[i].fileDownloadUri + "</a></p>";
// }
var endDate = new Date();
var diff = endDate - startDate;
multipleFileUploadSuccess.innerHTML = content + "time taken :::: " + diff;
multipleFileUploadSuccess.style.display = "block";
} else {
multipleFileUploadSuccess.style.display = "none";
multipleFileUploadError.innerHTML = (response && response.message) || "Some Error Occurred";
}
}
// console.log(xhr.responseText);
xhr.send(formData);
}
singleUploadForm.addEventListener('submit', function(event){
var files = singleFileUploadInput.files;
if(files.length === 0) {
singleFileUploadError.innerHTML = "Please select a file";
singleFileUploadError.style.display = "block";
}
uploadSingleFile(files[0]);
event.preventDefault();
}, true);
multipleUploadForm.addEventListener('submit', function(event){
var files = multipleFileUploadInput.files;
if(files.length === 0) {
multipleFileUploadError.innerHTML = "Please select at least one file";
multipleFileUploadError.style.display = "block";
}
uploadMultipleFiles(files);
event.preventDefault();
}, true);
asyncMltipleUploadForm.addEventListener('submit', function(event){
var files = asyncMultipleFileUploadInput.files;
if(files.length === 0) {
asyncMultipleFileUploadError.innerHTML = "Please select at least one file";
asyncMultipleFileUploadError.style.display = "block";
}
asynchUploadMultipleFiles(files);
event.preventDefault();
}, true);
Can you please help

Related

HTML form send data to google sheet with time stamp

i have success send data to my google sheet from HTML
function submit_form() {
var complete = true;
var error_color = '#FFD9D9';
var fields = ['name','phonenum','monthlysalary','totalamount','types'];
var row = '';
var i;
for(i=0; i < fields.length; ++i) {
var field = fields[i];
$('#'+field).css('backgroundColor', 'inherit');
var value = $('#'+field).val();
if(!value) {
if(field != 'message') {
$('#'+field).css('backgroundColor', error_color);
var complete = false;
}
} else {
row += '"'+value+'",';
}
}
if(complete) {
row = row.slice(0, -1);
var gs_sid = 'xxx';
var gs_clid = 'xxx';
var gs_clis = 'xxx';
var gs_rtok = 'xxx';
var gs_atok = false;
var gs_url = 'https://sheets.googleapis.com/v4/spreadsheets/'+gs_sid+'/values/Google!A1:append?includeValuesInResponse=false&insertDataOption=INSERT_ROWS&responseDateTimeRenderOption=SERIAL_NUMBER&responseValueRenderOption=FORMATTED_VALUE&valueInputOption=USER_ENTERED';
var gs_body = '{"majorDimension":"ROWS", "values":[['+row+']]}';
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://www.googleapis.com/oauth2/v4/token?client_id='+gs_clid+'&client_secret='+gs_clis+'&refresh_token='+gs_rtok+'&grant_type=refresh_token');
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
var response = JSON.parse(xhr.responseText);
var gs_atok = response.access_token;
if(gs_atok) {
var xxhr = new XMLHttpRequest();
xxhr.open('POST', gs_url);
xxhr.setRequestHeader('Content-type', 'application/json');
xxhr.setRequestHeader('Authorization', 'OAuth ' + gs_atok );
xxhr.send(gs_body);
}
};
xhr.send();
}
}
Now i having a problem, i would like to make the google sheets will auto adding timestamp when i send the data into google form. Its anyway to do it?
Thank you

Blob data is not being sent to the PHP through XHR

I am trying to chunk a file and send to the server as follows
var fileselect = document.getElementById("file");
fileselect.addEventListener("change", FileSelectHandler, false);
function FileDragHover(e) {
e.stopPropagation();
e.preventDefault();
}
function FileSelectHandler(e) {
FileDragHover(e);
var blob = e.target.files[0] || e.dataTransfer.files[0];
worker = new Worker("fileupload.js");
worker.postMessage(blob);
worker.onmessage = function(e) {
console.log(e);
};
}
fileupload.js
self.onmessage = function(e) {
const BYTES_PER_CHUNK = 1024 * 1024 * 32;
var blob = new Blob([e.data]),
start = 0,
index = 0,
slices = Math.ceil(blob.size / BYTES_PER_CHUNK),
slices2 = slices;
while (start < blob.size) {
end = start + BYTES_PER_CHUNK;
if (end > blob.size) end = blob.size;
uploadChunk(blob, index, start, end, slices, slices2);
start = end;
index++;
}
};
function uploadChunk(blob, index, start, end, slices, slices2) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
slices--;
if (slices == 0) {
var xhrMerge = new XMLHttpRequest();
xhrMerge.open("POST", "uploadlargefile/?a=merge&name=" + blob.name + "&slices=" + slices2);
xhrMerge.onload = function() {
self.close();
};
xhrMerge.send();
}
};
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) self.postMessage(Math.round(100 / e.total * e.loaded)); //this doesn't work o.O
};
var chunk = blob.slice(start, end);
xhr.open("POST", "uploadlargefile/?a=chunk&name=" + blob.name + "&index=" + index);
xhr.setRequestHeader("Content-Type", "multipart\/form-data; boundary=--------------------");
xhr.send(chunk);
}
PHP
print_r($_GET['name']); print_r($_FILES);die;
I am able to get the name of the file but not the file . Any suggestion what could be wrong

Ajax refresher for XMLhttprequest

I want the XML doc to get read on a fixed interval, and avoid full page refresh everytime it looks for updates. The code below which is commented out works, but messes up the JQuery cycle. (which is based on http://buildinternet.com/project/totem/ )
Need some help with this.
//function refresh()
// {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "drift.xml", true);
xhttp.send();
// }
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var item = xmlDoc.getElementsByTagName("item");
var itemlength = item.length;
var i;
var html='';
var today = new Date();
var aktuella = [];
$("#wrapper").append('<ul id=\'wrap\'></ul>');
for (i = 0; i < itemlength; i++) {
var postDate = xmlDoc.getElementsByTagName("expires")[i].childNodes[0].nodeValue;
var date = postDate.substring(8, 10);
var month = postDate.substring(5, 7);
var year = postDate.substring(0, 4);
var expiredDate = new Date(year, month - 1, date);
if (expiredDate > testDate) {
aktuella.push(i);
}
};
if (aktuella.length == 0 ) {
var none = "<p>Info</p>";
$('#wrapper').prepend(none);
};
if (aktuella.length == 1) {
var expires = '<p>' + xmlDoc.getElementsByTagName("expires")[0].parentNode.childNodes[1].textContent + '</p>';
$('#wrapper').prepend(expires);
};
if (aktuella.length > 1) {
for (i = 0; i < aktuella.length; i++) {
var expires = '<li id="' + i + '">' + xmlDoc.getElementsByTagName("expires")[i].parentNode.childNodes[1].textContent + ' - Se Driftinfo</li>';
$('#wrap').prepend(expires);
};
};
$(function(){
$('#wrap').totemticker({
row_height : '120px',
next : '#ticker-next',
previous : '#ticker-previous',
stop : null,
start : null,
mousestop : true,
});
});
}
// refresh();
// setInterval("refresh()", 5000);
</script>
Simple:
Add this ti your script:
setInterval(function(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
}, milliseconds);
try now with this. There where a mistake. funtion instead function and the interval after the function to call
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var item = xmlDoc.getElementsByTagName("item");
var itemlength = item.length;
var i;
var html='';
var today = new Date();
var aktuella = [];
$("#wrapper").append('<ul id=\'wrap\'></ul>');
for (i = 0; i < itemlength; i++) {
var postDate = xmlDoc.getElementsByTagName("expires") [i].childNodes[0].nodeValue;
var date = postDate.substring(8, 10);
var month = postDate.substring(5, 7);
var year = postDate.substring(0, 4);
var expiredDate = new Date(year, month - 1, date);
if (expiredDate > testDate) {
aktuella.push(i);
}
};
setInterval(function(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "drift.xml", true);
xhttp.send();
}, milliseconds);
Here is the site without any attempt to refresh the ajax:
http://socialsiberia.com/dash/test1.html
And here is the weird behaviour that occurs when I add the code below:
http://socialsiberia.com/dash/test2.html
setInterval(function(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "test.xml", true);
xhttp.send();
}, 5000);
var xhttp = new XMLHttpRequest();
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var item = xmlDoc.getElementsByTagName("item");
var itemlength = item.length;
var i;
var html='';
var today = new Date();
var aktuella = [];
$("#wrapper").append('<ul id=\'wrap\'></ul>');
for (i = 0; i < itemlength; i++) {
var postDate = xmlDoc.getElementsByTagName("expires")[i].childNodes[0].nodeValue;
var date = postDate.substring(8, 10);
var month = postDate.substring(5, 7);
var year = postDate.substring(0, 4);
var expiredDate = new Date(year, month - 1, date);
if (expiredDate > testDate) {
aktuella.push(i);
}
};
if (aktuella.length == 0 ) {
var none = "<p>Info</p>";
$('#wrapper').prepend(none);
};
if (aktuella.length == 1) {
var expires = '<p>' + xmlDoc.getElementsByTagName("expires")[0].parentNode.childNodes[1].textContent + '</p>';
$('#wrapper').prepend(expires);
};
if (aktuella.length > 1) {
for (i = 0; i < aktuella.length; i++) {
var expires = '<li id="' + i + '">' + xmlDoc.getElementsByTagName("expires")[i].parentNode.childNodes[1].textContent + ' - Se Driftinfo</li>';
$('#wrap').prepend(expires);
};
};
$(function(){
$('#wrap').totemticker({
row_height : '120px',
next : '#ticker-next',
previous : '#ticker-previous',
stop : null,
start : null,
mousestop : true,
});
});
}
funtion makeinterval(){
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "drift.xml", true);
xhttp.send();
}
setInterval(function(){
makeInterval();
}, 5000);
makeinterval()

JavaScript upload progress bar with xhr.status error 500, but one file loads

I've got a problem with a script that is used to upload one or more multipart/form-data files.
On my client's server, when I try to upload more than one file, I receive:
xhr.status error 500;
The first file is uploaded okay, but I can't upload more than 1 file. On my server, everything works fine - there is no error 500.
I have searched the web for help, but I could only find information about server problems, such as: can not accept POST, GET, OPTIONS...
But it's working with one file - and I'm stuck.
I tried to upload the files one by one, but then my progress bar is flashing like....
Here is my code:
$(document).ready( function() {
$(".errorNotice").hide();
});
var form = document.getElementById('upload-form');
var ident = document.getElementById('ident');
var fileSelect = document.getElementById('file-select');
var uploadButton = document.getElementById('submit');
var max = document.getElementById('max');
var formUrl = form.action;
function sleep(milliseconds) {
setTimeout(function(){ return true; }, milliseconds);
}
form.onsubmit = function(event) {
event.preventDefault();
uploadButton.innerHTML = 'Trwa ładowanie...';
$("#upload-form").fadeOut();
setTimeout(function() {
$("#progressBar").fadeIn();
}, 500);
var files = fileSelect.files;
var formData = new FormData();
if( files.length > max.value) {
if( max.value == 1) {
var text = max.value + ' zdjęcie';
}
else if( max.value >1 && max.value <= 4) {
var text = max.value + ' zdjęcia';
}
else {
var text = max.value + ' zdjęć';
}
$("#progressBar").find("p").html('Możesz dodać maksymalnie: ' + text);
setTimeout(function() {
$("#progressBar").hide();
$("#upload-form").fadeIn();
}, 5000);
return false;
}
if( files.length == 0 )
{
$("#progressBar").hide();
$("#upload-form").show();
}
formData.append('ident', ident.value);
formData.append('modules', 'true');
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.type.match('image.*')) {
continue;
}
formData.append('objectPhoto[]', file, file.name);
formData.append(name, file, file.name);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', formUrl , true);
xhr.upload.addEventListener("progress", function(e) {
if(e.lengthComputable) {
var percentage = Math.round((e.loaded * 100) / e.total);
document.getElementById("bar").style.width = percentage + '%';
document.getElementById("percent").innerHTML = percentage + '%';
}
}, false);
xhr.onload = function () {
console.log(this.responseText);
if(this.responseText == "ok") {
document.getElementById("percent").innerHTML = "Zakończono";
document.getElementById("progressBar").style.display = "none";
document.getElementById("upload-form").style.display = "block";
} else {
$(".errorNotice").show();
$(".errorNotice .error-text").html(this.responseText);
}
if (xhr.status === 200) {
uploadButton.innerHTML = 'Wgraj';
} else {
$(".errorNotice").show();
$(".errorNotice .error-text").html("Wystąpił nieoczekiwany błąd o kodzie: " + xhr.status);
uploadButton.innerHTML = 'Wyślij';
}
};
xhr.send(formData);
return false;
};

Downloading binary data using XMLHttpRequest, without overrideMimeType

I am trying to retrieve the data of an image in Javascript using XMLHttpRequest.
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.celticfc.net/images/doc/celticcrest.png");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
var resp = xhr.responseText;
console.log(resp.charCodeAt(0) & 0xff);
}
};
xhr.send();
The first byte of this data should be 0x89, however any high-value bytes return as 0xfffd (0xfffd & 0xff being 0xfd).
Questions such as this one offer solutions using the overrideMimeType() function, however this is not supported on the platform I am using (Qt/QML).
How can I download the data correctly?
Google I/O 2011: HTML5 Showcase for Web Developers: The Wow and the How
Fetch binary file: new hotness
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.celticfc.net/images/doc/celticcrest.png', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
var uInt8Array = new Uint8Array(this.response); // Note:not xhr.responseText
for (var i = 0, len = uInt8Array.length; i < len; ++i) {
uInt8Array[i] = this.response[i];
}
var byte3 = uInt8Array[4]; // byte at offset 4
}
}
xhr.send();
I'm not familiarized with Qt but i found this in their documentation
string Qt::btoa ( data )
Binary to ASCII - this function returns a base64 encoding of data.
So, if your image is a png you can try:
resp = "data:image/png;base64," + btoa(resp);
document.write("<img src=\""+resp+"\">");
Qt version 5.13.1(support native Promise in qml env), prue qml.
function fetch, like node-fetch
function hexdump, dump the data as hex, just use the linux command hexdump to check.
function createResponse(xhr) {
let res = {};
function headersParser() {
let headersRaw = {};
let lowerCaseHeaders = {};
let rawHeaderArray = xhr.getAllResponseHeaders().split("\n");
for(let i in rawHeaderArray) {
let rawHeader = rawHeaderArray[i];
let headerItem = rawHeader.split(":");
let name = headerItem[0].trim();
let value = headerItem[1].trim();
let lowerName = name.toLowerCase();
headersRaw[name] = value;
lowerCaseHeaders [lowerName] = value;
}
return {
"headersRaw": headersRaw,
"lowerCaseHeaders": lowerCaseHeaders
};
}
res.headers = {
__alreayParse : false,
raw: function() {
if (!res.headers.__alreayParse) {
let {headersRaw, lowerCaseHeaders} = headersParser();
res.headers.__alreayParse = true;
res.headers.__headersRaw = headersRaw;
res.headers.__lowerCaseHeaders = lowerCaseHeaders;
}
return res.headers.__headersRaw;
},
get: function(headerName) {
if (!res.headers.__alreayParse) {
let {headersRaw, lowerCaseHeaders} = headersParser();
res.headers.__alreayParse = true;
res.headers.__headersRaw = headersRaw;
res.headers.__lowerCaseHeaders = lowerCaseHeaders;
}
return res.headers.__lowerCaseHeaders[headerName.toLowerCase()];
}
};
res.json = function() {
if(res.__json) {
return res.__json;
}
return res.__json = JSON.parse(xhr.responseText);
}
res.text = function() {
if (res.__text) {
return res.__text;
}
return res.__text = xhr.responseText;
}
res.arrayBuffer = function() {
if (res.__arrayBuffer) {
return res.__arrayBuffer;
}
return res.__arrayBuffer = new Uint8Array(xhr.response);
}
res.ok = (xhr.status >= 200 && xhr.status < 300);
res.status = xhr.status;
res.statusText = xhr.statusText;
return res;
}
function fetch(url, options) {
return new Promise(function(resolve, reject) {
let requestUrl = "";
let method = "";
let headers = {};
let body;
let timeout;
if (typeof url === 'string') {
requestUrl = url;
method = "GET";
if (options) {
requestUrl = options['url'];
method = options['method'];
headers = options['headers'];
body = options['body'];
timeout = options['timeout'];
}
} else {
let optionsObj = url;
requestUrl = optionsObj['url'];
method = optionsObj['method'];
headers = optionsObj['headers'];
body = optionsObj['body'];
timeout = optionsObj['timeout'];
}
let xhr = new XMLHttpRequest;
if (timeout) {
xhr.timeout = timeout;
}
// must set responseType to arraybuffer, then the xhr.response type will be ArrayBuffer
// but responseType not effect the responseText
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = function() {
// readyState as follow: UNSENT, OPENED, HEADERS_RECEIVED, LOADING, DONE
if(xhr.readyState === XMLHttpRequest.DONE) {
resolve(createResponse(xhr));
}
};
xhr.open(method, requestUrl);
// todo check headers
for(var iter in headers) {
xhr.setRequestHeader(iter, headers[iter]);
}
if("GET" === method || "HEAD" === method) {
xhr.send();
} else {
xhr.send(body);
}
});
}
function hexdump(uint8array) {
let count = 0;
let line = "";
let lineCount = 0;
let content = "";
for(let i=0; i<uint8array.byteLength; i++) {
let c = uint8array[i];
let hex = c.toString(16).padStart (2, "0");
line += hex + " ";
count++;
if (count === 16) {
let lineCountHex = (lineCount).toString (16).padStart (7, "0") + "0";
content += lineCountHex + " " + line + "\n";
line = "";
count = 0;
lineCount++;
}
}
if(line) {
let lineCountHex = (lineCount).toString (16).padStart (7, "0") + "0";
content += lineCountHex + " " + line + "\n";
line = "";
// count = 0;
lineCount++;
}
content+= (lineCount).toString (16).padStart (7, "0") + count.toString(16) +"\n";
return content;
}
fetch("https://avatars2.githubusercontent.com/u/6630355")
.then((res)=>{
try {
let headers = res.headers.raw();
console.info(`headers:`, JSON.stringify(headers));
let uint8array = res.arrayBuffer();
let hex = hexdump(uint8array);
console.info(hex)
}catch(error) {
console.trace(error);
}
})
.catch((error)=>{
});

Categories

Resources