How to get xhtmlrequest response? - javascript

How can I get here the Response from my PHP File?
client.responseText isnt working
I dont know what to type left here but it says it needs more Details?
So i try to code atm a File Upload and this is a small beginn of it but for error handling i need to know the Response.
function fileChange() {
var fileList = document.getElementById("fileA").files;
//File Objekt (erstes Element der FileList)
var file = fileList[0];
//File Objekt nicht vorhanden = keine Datei ausgewählt oder vom Browser nicht unterstützt
if (!file)
return;
document.getElementById("fileName").innerHTML = 'Dateiname: ' + file.name;
document.getElementById("fileSize").innerHTML = 'Dateigröße: ' + file.size + ' B';
document.getElementById("fileType").innerHTML = 'Dateitype: ' + file.type;
document.getElementById("progress").value = 0;
document.getElementById("prozent").innerHTML = "0%";
}
var client = null;
function uploadFile() {
//Wieder unser File Objekt
var file = document.getElementById("fileA").files[0];
var interpret = document.getElementById("interpret").value;
var title = document.getElementById("title").value;
alert(interpret);
alert(title);
//FormData Objekt erzeugen
var formData = new FormData();
//XMLHttpRequest Objekt erzeugen
client = new XMLHttpRequest();
var prog = document.getElementById("progress");
if (!file)
return;
prog.value = 0;
prog.max = 100;
formData.append("datei", file);
formData.append("interpret", interpret);
formData.append("title", title);
client.onerror = function(e) {
alert("onError");
};
client.onload = function(e) {
document.getElementById("prozent").innerHTML = "100%";
prog.value = prog.max;
};
client.upload.onprogress = function(e) {
var p = Math.round(100 / e.total * e.loaded);
document.getElementById("progress").value = p;
document.getElementById("prozent").innerHTML = p + "%";
};
client.onabort = function(e) {
alert("Upload abgebrochen");
};
client.open("POST", "./ajax/fileupload.php");
client.send(formData);
}
function uploadAbort() {
if (client instanceof XMLHttpRequest)
client.abort();
}

Related

XMLHttpRequest stream crashing when uploading large files (~1 GB)

I'm trying to make an online file manager for another project with friends, and when uploading files bigger than 1GB, the process either crashes (firefox), or succeeds but the received file weighs 0 bytes (chromium).
JS:
function uploadFile(fileInputId, fileIndex) {
//send file name
try {
var fileName = document.getElementById('fileUploader').files[0].name;
}
catch {
document.getElementById('uploadStatus').innerHTML = `<font color="red">Mettre un fichier serait une bonne idée.</font>`;
return false;
}
document.cookie = 'fname=' + fileName;
//take file from input
const file = document.getElementById(fileInputId).files[fileIndex];
const reader = new FileReader();
reader.readAsBinaryString(file);
reader.onloadend = function(event) {
ajax = new XMLHttpRequest();
//send data
ajax.open("POST", 'uploader.php', true);
//all browser supported sendAsBinary
XMLHttpRequest.prototype.mySendAsBinary = function(text) {
var data = new ArrayBuffer(text.length);
var ui8a = new Uint8Array(data, 0)
for (var i = 0; i < text.length; i++) ui8a[i] = (text.charCodeAt(i) & 0xff);
if (typeof window.Blob == "function") {
var blob = new Blob([data]);
}else {
var bb = new (window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder)();
bb.append(data);
var blob = bb.getBlob();
}
this.send(blob);
}
//track progress
var eventSource = ajax.upload || ajax;
eventSource.addEventListener('progress', function(e) {
//percentage
var position = e.position || e.loaded;
var total = e.totalSize || e.total;
var percentage = Math.round((position/total)*100);
document.getElementById('uploadStatus').innerHTML = `${percentage}%`;
});
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
document.getElementById('uploadStatus').innerHTML = this.responseText;
}
}
ajax.mySendAsBinary(event.target.result);
}
}
PHP:
//mysql login
$conn = new PDO([Redacted]);
//file info
$fileName = $_COOKIE['fname'];
$targetDir = "uploads/";
$targetFile = $targetDir.$fileName;
$fileNameRaw = explode('.', $fileName)[0]; //file name with no extension
$tempFilePath = $targetDir.$fileNameRaw.'.tmp';
if (file_exists($targetFile)) {
echo '<font color="red">Un fichier du même nom existe déjà.</font>';
exit();
}
//read from stream
$inputHandler = fopen('php://input', 'r');
//create temp file to store data from stream
$fileHandler = fopen($tempFilePath, 'w+');
//store data from stream
while (true) {
$buffer = fgets($inputHandler, 4096);
if (strlen($buffer) == 0) {
fclose($inputHandler);
fclose($fileHandler);
break;
}
fwrite($fileHandler, $buffer);
}
//when finished
rename($tempFilePath, $targetFile);
chmod($targetFile, 0777);
echo 'Fichier envoyé avec succès !';
$bddInsert = $conn->prepare('INSERT INTO files(nom, chemin) VALUES(?,?)');
$bddInsert->execute(array($fileName, $targetFile));
in my php.ini,
max_execution_time is set to 0
max_input_time to -1
and my post max and upload max sizes are at 4G
I'm using apache2
You should not be reading the file with the fileReader if you don't need it.
Just send the file (blob) directly to your ajax request and avoid the FileReader
function uploadFile (fileInputId, fileIndex) {
// Send file name
try {
var fileName = document.getElementById('fileUploader').files[0].name;
}
catch {
document.getElementById('uploadStatus').innerHTML = `<font color="red">Mettre un fichier serait une bonne idée.</font>`;
return false;
}
document.cookie = 'fname=' + fileName;
// Take file from input
const file = document.getElementById(fileInputId).files[fileIndex];
const ajax = new XMLHttpRequest();
// send data
ajax.open("POST", 'uploader.php', true);
// track progress
ajax.upload.addEventListener('progress', function(e) {
// percentage
var position = e.position || e.loaded;
var total = e.totalSize || e.total;
var percentage = Math.round((position/total)*100);
document.getElementById('uploadStatus').innerHTML = `${percentage}%`;
});
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
document.getElementById('uploadStatus').innerHTML = this.responseText;
}
}
ajax.send(file)
}

Phonegap: FileTransferError.FILE_NOT_FOUND_ERR

I'm using the Phonegap file transfer plugin to upload a picture to the server. However I am getting error code: 1 (FileTransferError.FILE_NOT_FOUND_ERR). I've tested my server code with POSTMAN and I can upload and image successfully. However I get that error with the plugin. This is my code. The file is declared from "camera_image.src" and I can see the image when I append this to the src of an image on the fly. Any contributions? How is this code not perfect?
var fileURL = camera_image.src;
alert(fileURL);
var win = function (r) {
temp.push(r.response);
statusDom.innerHTML = "Upload Succesful!";
}
var fail = function (error) {
alert("An error has occurred: Code = " + error.code + " | Source:" + error.source + " | Target:" + error.target );
statusDom.innerHTML = "Upload failed!";
}
var options = new FileUploadOptions();
options.fileKey = "properties_photo";
options.fileName=fileURL.substr(fileURL.lastIndexOf('/') + 1);
options.headers = {
Connection: "close"
};
var params = {};
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
statusDom = document.querySelector('#status');
ft.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable) {
var perc = Math.floor(progressEvent.loaded / progressEvent.total * 100);
statusDom.innerHTML = perc + "% uploaded...";
console.log(perc);
} else {
if(statusDom.innerHTML == "") {
statusDom.innerHTML = "Loading";
} else {
statusDom.innerHTML += ".";
}
}
};
ft.upload(fileURL, encodeURI("http://cloud10.me/clients/itsonshow/app/image_upload_process.php"), win, fail, options);
I had this problem because of spaces in the path or filename of the file to be uploaded.
You need to ensure the plugin isn't being passed a fileURL with %20 in the URL.

Multiple XMLHttpRequest.send or eventlisteners memory leak?

I'm currently implementing an upload for files. Because I've to handle huge files here and there I've started to slice files and send them in 1mb chunks which works great as long as file are <~500MB after that it seems that memory isn't freed anyone randomly and I can't figure out what I'm missing here.
Prepare chunks
var sliceCount = 0;
var sendCount = 0;
var fileID = generateUUID();
var maxChunks = 0;
var userNotified = false;
function parseFile(file)
{
var fileSize = file.size;
var chunkSize = 1024 * 1024;//64 * 1024; // bytes
var offset = 0;
var self = this; // we need a reference to the current object
var chunkReaderBlock = null;
var numberOfChunks = fileSize / chunkSize;
maxChunks = Math.ceil(numberOfChunks);
// gets called if chunk is read into memory
var readEventHandler = function (evt)
{
if (evt.target.error == null) {
offset += evt.target.result.byteLength;
sendChunkAsBinary(evt.target.result);
}
else
{
console.log("Read error: " + evt.target.error);
return;
}
if (offset >= fileSize) {
console.log("Done reading file");
return;
}
// of to the next chunk
chunkReaderBlock(offset, chunkSize, file);
}
chunkReaderBlock = function (_offset, length, _file)
{
var r = new FileReader();
var blob = _file.slice(_offset, length + _offset);
sliceCount++;
console.log("Slicecount: " + sliceCount);
r.onload = readEventHandler;
r.readAsArrayBuffer(blob);
blob = null;
r = null;
}
// now let's start the read with the first block
chunkReaderBlock(offset, chunkSize, file);
}
Send Chunks
function sendChunkAsBinary(chunk)
{
var progressbar = $("#progressbar"), bar = progressbar.find('.uk-progress-bar');
// create XHR instance
var xhr = new XMLHttpRequest();
// send the file through POST
xhr.open("POST", 'upload.php', true);
var progressHandler = function (e)
{
// get percentage of how much of the current file has been sent
var position = e.loaded || e.position;
var total = e.total || e.totalSize;
var percentage = Math.round((sendCount / maxChunks) * 100);
// set bar width to keep track of progress
bar.css("width", percentage + "%").text(percentage + "%");
}
// let's track upload progress
var eventSource = xhr.upload || xhr;
eventSource.addEventListener("progress", progressHandler);
// state change observer - we need to know when and if the file was successfully uploaded
xhr.onreadystatechange = function ()
{
if (xhr.readyState == 4)
{
if (xhr.status == 200)
{
eventSource.removeEventListener("progress", progressHandler);
if (sendCount == maxChunks && !userNotified)
{
userNotified = true;
notifyUserSuccess("Datei hochgeladen!");
setTimeout(function ()
{
progressbar.addClass("uk-invisible");
bar.css("width", "0%").text("0%");
}, 250);
updateDocList();
}
}
else
{
notifyUser("Fehler beim hochladen der Datei!");
}
}
};
var blob;
if (typeof window.Blob == "function") {
blob = new Blob([chunk]);
} else {
var bb = new (window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder)();
bb.append(chunk);
blob = bb.getBlob();
}
sendCount++;
var formData = new FormData();
formData.append("chunkNumber", sendCount);
formData.append("maxChunks", maxChunks);
formData.append("fileID", fileID);
formData.append("chunkpart", blob);
xhr.send(formData);
progressbar.removeClass("uk-invisible");
console.log("Sendcount: " + sendCount);
}
If I attach to the debugger within Visual Studio 2015 it take a bit but soon I get an OutOfMemoryException in the send function at exactly this line: blob = new Blob([chunk]);. It's all the time the same line where the exception occures.
As soon as the Exception happens I get POST [...]/upload.php net::ERR_FILE_NOT_FOUND however I still got the chunks in my php-file.
Here's a Timeline-graph of my error
What I dont understand, I'm not able to see increasing memory inside the Task-Manager (a few mb of course but not close to 16gb ram I got).
So can anyone tell me where this leak comes from? What am I missing?

Video and audio create with mp4 file

In this code create only Video on chrome, i want video with Audio with one mp4/webm file. is it possible in PHP?
please give me helpful solutions.
var mediaConstraints = { audio: true, video: true };
//var isFirefox = true;
document.querySelector('#start-recording').onclick = function() {
this.disabled = true;
navigator.getUserMedia(mediaConstraints, onMediaSuccess, onMediaError);
};
document.querySelector('#stop-recording').onclick = function() {
this.disabled = true;
mediaRecorder.stop();
};
var mediaRecorder;
function onMediaSuccess(stream) {
var video = document.createElement('video');
var videoWidth = document.getElementById('video-width').value || 320;
var videoHeight = document.getElementById('video-height').value || 240;
video = mergeProps(video, {
controls: true,
id:"preview",
width: videoWidth,
height: videoHeight,
src: URL.createObjectURL(stream)
});
video.play();
//videot='2000';
videosContainer.appendChild(video);
videosContainer.appendChild(document.createElement('hr'));
mediaRecorder = new MediaStreamRecorder(stream);
mediaRecorder.mimeType = 'video/mp4'; // this line is mandatory
mediaRecorder.videoWidth = videoWidth;
mediaRecorder.videoHeight = videoHeight;
mediaRecorder.ondataavailable = function(blob) {
//alert(blob.audio);
//alert(blob.video);
// var a = document.createElement('a');
// a.target = '_blank';
// a.innerHTML = 'Open Recorded Video No. ' + (index++) + ' (Size: ' + bytesToSize(blob.size) + ') Time Length: ' + getTimeLength(timeInterval);
// a.href = URL.createObjectURL(blob);
//videosContainer.appendChild(a);
// videosContainer.appendChild(document.createElement('hr'));
var facedeteval = document.getElementById('facedetectvalue').value;
if(facedeteval !='1')
{
//alert(facedeteval);
var testuserID = document.getElementById("tuid").value;
var capId =document.getElementById("capimg").value;
//alert(capId);
var fileType = 'video'; // or "audio"
var vname = document.getElementById('sect_id').value;
var res = vname;
fileName =res;
var fileName = res+(index++)+'.mp4'; // or "wav" or "ogg"
var formData = new FormData();
formData.append(fileType + '-filename', fileName);
formData.append(fileType + '-blob', blob);
formData.append('test_uid', testuserID);
formData.append('cap_id', capId);
function xhr(url, data, callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
callback(location.href + request.responseText);
}
};
request.open('POST', url);
request.send(data);
}
xhr('save.php', formData, function (fileURL) {
alert('video save');
stopflag = '0';
document.getElementById('facedetectvalue').value = '1';
});
}
};
var timeInterval = document.querySelector('#time-interval').value;
if(timeInterval) timeInterval = parseInt(timeInterval);
else timeInterval = 5 * 1000;
// get blob after specific time interval
mediaRecorder.start(timeInterval);
document.querySelector('#stop-recording').disabled = false;
}
function onMediaError(e) {
console.error('media error', e);
}
var videosContainer = document.getElementById('videos-container');
var index = 1;
// below function via: http://goo.gl/B3ae8c
function bytesToSize(bytes) {
var k = 1000;
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes === 0) return '0 Bytes';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(k)),10);
return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
}
// below function via: http://goo.gl/6QNDcI
function getTimeLength(milliseconds) {
var data = new Date(milliseconds);
return data.getUTCHours()+" hours, "+data.getUTCMinutes()+" minutes and "+data.getUTCSeconds()+" second(s)";
}
window.onbeforeunload = function() {
document.querySelector('#start-recording').disabled = false;
};

Progress event listeners to load thumbnails one at a time

I am working on around 40 Large images each of size 9000KB.
i have below code ,all images are loading at a time which makes my screen to freeze,I want that my control will wait until the first image is successfully progress then loads completely then move on to the next one.any idea is helpful..
//dropping around 40 images
dropbox.addEventListener("drop", dropUpload, false);
function dropUpload(event) {
noop(event);
var dropMethod = event.dataTransfer;
var classicMethod = event.target;
var dropedFiles = (dropMethod == undefined) ? classicMethod.files: dropMethod.files;
for ( var i = 0; i < dropedFiles.length; i++) {
addFilesToUpload(dropedFiles[i]);
}
}
function addFilesToUpload(file) {
var li = document.createElement("li"), div = document.createElement("div"), img, progressBarContainer = document
.createElement("div"), progressBar = document.createElement("div"), tBody;
li.appendChild(div);
progressBarContainer.className = "progress-bar-container";
progressBar.className = "progress-bar";
progressBar.setAttribute("id", "proBar_" + (indexN++));
progressBarContainer.appendChild(progressBar);
li.appendChild(progressBarContainer);
var reader = new FileReader();
reader.onerror = function(event) {
alert("couldn't read file " + event.target.error.code);
};
// Present file info and append it to the list of files
fileInfo = "<div><strong>Name:</strong> " + file.name + "</div>";
fileInfo += "<div><strong>Size:</strong> " + parseInt(file.size / 1024, 10)
+ " kb</div>";
fileInfo += "<div><strong>Type:</strong> " + file.type + "</div>";
div.innerHTML = fileInfo;
if (reader !== "undefined" && (/image/i).test(file.type)) {
img = document.createElement("img");
img.setAttribute("class", "thumb");
img.setAttribute("id", "img_" + (indexN++));
reader.onload = (function(img, li) {
return function(evt) {
img.src = evt.target.result;
img.file = file;
};
}(img, li));
reader.readAsDataURL(file);
}
reader.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
progressBar.style.width = (evt.loaded / evt.total) * 100 + "%";
}
}, false);
reader.addEventListener("load", function() {
progressBarContainer.className += " uploaded";
progressBar.innerHTML = "";
}, false);
tBody = getTableBodyLayout(img, li);
document.getElementById("images_table").appendChild(tBody);
}
You can change addFilesToUpload() to take a callback when the file is done and change dropUpload() to initiate one at a time.
function dropUpload(event) {
noop(event);
var dropMethod = event.dataTransfer;
var classicMethod = event.target;
var dropedFiles = (dropMethod == undefined) ? classicMethod.files: dropMethod.files;
var filesDone = 0;
// local function to process the next file
function next() {
if (filesDone < dropedFiles.length) {
addFilesToUpload(dropedFiles[filesDone++], next);
}
}
// do the first one
next();
}
function addFilesToUpload(file, doneCallback) {
var li = document.createElement("li"), div = document.createElement("div"), img, progressBarContainer = document
.createElement("div"), progressBar = document.createElement("div"), tBody;
li.appendChild(div);
progressBarContainer.className = "progress-bar-container";
progressBar.className = "progress-bar";
progressBar.setAttribute("id", "proBar_" + (indexN++));
progressBarContainer.appendChild(progressBar);
li.appendChild(progressBarContainer);
var reader = new FileReader();
reader.onerror = function(event) {
alert("couldn't read file " + event.target.error.code);
};
// Present file info and append it to the list of files
fileInfo = "<div><strong>Name:</strong> " + file.name + "</div>";
fileInfo += "<div><strong>Size:</strong> " + parseInt(file.size / 1024, 10)
+ " kb</div>";
fileInfo += "<div><strong>Type:</strong> " + file.type + "</div>";
div.innerHTML = fileInfo;
if (reader !== "undefined" && (/image/i).test(file.type)) {
img = document.createElement("img");
img.setAttribute("class", "thumb");
img.setAttribute("id", "img_" + (indexN++));
reader.onload = (function(img, li) {
return function(evt) {
img.src = evt.target.result;
img.file = file;
// call the callback to tell the caller that this file is done now
doneCallback();
};
}(img, li));
reader.readAsDataURL(file);
}
reader.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
progressBar.style.width = (evt.loaded / evt.total) * 100 + "%";
}
}, false);
reader.addEventListener("load", function() {
progressBarContainer.className += " uploaded";
progressBar.innerHTML = "";
}, false);
tBody = getTableBodyLayout(img, li);
document.getElementById("images_table").appendChild(tBody);
}
If you want to wait to proceed to the next image until each image has loaded, then you could change the reader.onload handler to this:
reader.onload = (function(img, li) {
return function(evt) {
img.onload = function() {
// call the callback to tell the caller that this file is done now
doneCallback();
};
img.src = evt.target.result;
img.file = file;
};
}(img, li));

Categories