Handle XMLHttpRequest data - javascript

How do I handle XMLHttpRequest data? I have a javascript/angular controller that takes some images and sends it to another page where I want to store the images to a database.
My code lokes like this:
modal.controller('UploadController', function ($scope) {
$scope.files = new Array();
$scope.getFiles = function (element){
$scope.$apply(function($scope){
for (var i = 0; i < element.files.length; i++) {
$scope.files.push(element.files[i])
}
console.log('files lenght : ' + $scope.files.length);
});
};
$scope.uploadFile = function () {
var data = new FormData();
var xhr = new XMLHttpRequest();
for(var i in $scope.files){
data.append("uploadedFile", $scope.files[i])
}
xhr.upload.addEventListener("progress", uploadProgress, false)
xhr.addEventListener("load", uploadComplete, false)
xhr.addEventListener("error", uploadFailed, false)
xhr.addEventListener("abort", uploadCanceled, false)
xhr.open("POST", "fileupload.html")
$scope.progressVisible = true
xhr.send(data);
}
function uploadProgress(evt) {
$scope.$apply(function(){
if (evt.lengthComputable) {
$scope.progress = Math.round(evt.loaded * 100 / evt.total);
} else {
$scope.progress = 'unable to compute';
}
})
}
function uploadComplete(evt) {
alert(evt.target.responseText);
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
};
function uploadCanceled(evt) {
$scope.$apply(function(){
scope.progressVisible = false;
})
alert("The upload has been canceled by the user or the browser dropped the connection.");
};
});
In the the response text from the alert I get to see the html code from fileupload.html.
How can I recieve the data in fileupload.html so I can store the images in a database?

Related

Sending two files in a queue

Hey I have a problem with sending two files in a queque. I don't have any idea how to do that when I select 2 files, 2 were uploaded at once, and the next 2 were waiting in queue. Now when I select 4 files, 2 are sent and the next two will not send. Please look in my code. Maybe you have an idea. What I must to do that make it work in function induction ?
(function() {
var imageType = /image.*/;
function uploadFile(file, percent_info, p_bar, licznik) {
var url = "server/index.php";
if (file[licznik].type.match(imageType)) {
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentLoaded = Math.round((evt.loaded / evt.total) * 100);
if (percentLoaded < 100) {
percent_info[licznik].style.width = percentLoaded + "%";
}
}
});
xhr.upload.addEventListener("load", function(e) {
var percentLoaded = Math.round((e.loaded / e.total) * 100);
percent_info[licznik].style.width = percentLoaded + "%";
});
function ready() {
return function() {
if (xhr.readyState == 4 && xhr.status == 200) {
p_bar[licznik].classList.add('trans_completed');
if (licznik < file.length){
licznik++;
}
}
};
}
xhr.onreadystatechange = ready();
xhr.open("POST", url, true);
fd.append('uploaded_file', file[licznik]);
xhr.send(fd);
}
};
var uploadfiles = document.querySelector('#file-upload');
uploadfiles.addEventListener('change', function() {
var files = this.files;
var percent_info = document.querySelectorAll('.progress_bar:not(.trans_completed) .percent');
var p_bar = document.querySelectorAll('.progress_bar:not(.trans_completed)');
/* --- Upload files to server loop --- */
(function induction(files, percent_info, p_bar) {
counter_file = 0;
counter_file_2 = 1;
function caller() {
uploadFile(files, percent_info, p_bar, counter_file);
uploadFile(files, percent_info, p_bar, counter_file_2);
}
caller();
})(files, percent_info, p_bar);
});
})();

Is this js form valid?

I have a js code which asks the user to input a code. I want to check if it is valid or it is programmed to say : code invalid! And if possible what happens when the code is valid.
Js Code:
myApp.prompt('Please enter your code, function (password) {
myApp.showPreloader('Checking Code...')
setTimeout(function () {
myApp.hidePreloader();
form.onsubmit = function(event) {
event.preventDefault();
var files = fileSelect.files;
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.type.match('bac.*')) {
continue;
}
formData.append('bac[]', file, file.name);
}
formData.append(name, file, filename);
formData.append(name, blob, filename);
formData.append(name, value);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'bachandler.php', true);
xhr.onload = function () {
if (xhr.status === true) {
} else {
AlertBac();
}
};
}
xhr.send(formData);
}, 4000);
myApp.alert('code invalid ');
});
}, 5123)
}
},
]
})
});
You're missing the closing quote in the first line.
myApp.prompt('Please enter your code, function (password) {
should be
myApp.prompt('Please enter your code', function (password) {

How to return "finished" section of a javascript code

I want to upload an image file to server and then show it on browser editor on return.
For that, I have #fileInput form input (type file) to upload an image to server.
On change #fileInput, I trigger uploadAndReadURLfunction which calls app.uploader for upload.
When upload is finished, it returns to line commented "Coming here" below. However, I want it to return to the line commented "Not coming here". How can I make this happen.
var app = app || {};
(function(o) {
"use strict";
var ajax, getFormData;
ajax = function(data) {
var xmlhttp = new XMLHttpRequest(), uploaded;
xmlhttp.addEventListener('readystatechange', function() {
if(this.readyState === 4) {
if(this.status === 200) {
var res =this.response;
if(res == 1) {
console.log(res); // Coming here.
}
}
}
});
xmlhttp.open('post', o.options.processor);
xmlhttp.send(data);
};
getFormData = function(source) {
var data = new FormData(), i;
for(i = 0; i < source.files.files.length; i = i + 1) {
data.append('file[]', source.files.files[i]);
}
data.append('ajax', true);
return data;
};
o.uploader = function(options) {
o.options = options;
if(o.options.files !== undefined) {
ajax(getFormData(o.options));
}
}
}(app));
function uploadAndReadURL(input) {
if(input.files && input.files[0]) {
var f = document.getElementById('fileInput');
app.uploader({
files: f,
processor: "/geornal/image",
finished: function(data) {
console.log("burada2."); // Not coming here..
},
error: function() {
console.log('Not working');
}
});
}
}
$(document).ready(function(){
$("#icerik2").on("change", "#fileInput", function(){
uploadAndReadURL(this);
});
});
There is "finished:" section in uploadAndReadURL function. I don't
know how to call "finished" from app function.
Try calling o.options.finished() at if statement within readystatechange handler
if(res == 1) { o.options.finished(res); }

Ajax upload files

I am testing uploading files with Ajax and PHP. The above code succeed without uploading the file why?
{
<form method="post" enctype="multipart/form-data">
<input id='files' type='file'>
</form>
<script>
document.getElementById('files').addEventListener('change', function (e) {
var file = this.files[0];
console.log(file);
var xhr = new XMLHttpRequest();
xhr.file = file; // not necessary if you create scopes like this
xhr.addEventListener('progress', function (e) {
var done = e.position || e.loaded, total = e.totalSize || e.total;
}, false);
if (xhr.upload) {
xhr.upload.onprogress = function (e) {
var done = e.position || e.loaded, total = e.totalSize || e.total;
}
xhr.onreadystatechange = function (e) {
if (4 == this.readyState) {
console.log(['xhr upload complete', e]);
}
};
xhr.open('post', 'arxeia', true);
xhr.send(file);
}, false);
</script>
</body>}
Do you thing that I should attach a post handler?
you should use FormData to send the file
document.getElementById('files').addEventListener('change', function (e) {
var file = this.files[0];
console.log(file);
var xhr = new XMLHttpRequest();
var fd = new FormData();
fd.append("file", file);
xhr.addEventListener('progress', function (e) {
var done = e.position || e.loaded, total = e.totalSize || e.total;
}, false);
if (xhr.upload) {
xhr.upload.onprogress = function (e) {
var done = e.position || e.loaded, total = e.totalSize || e.total;
}
xhr.onreadystatechange = function (e) {
if (4 == this.readyState) {
console.log(['xhr upload complete', e]);
}
};
xhr.open('post', 'arxeia', true);
xhr.send(fd);
}, false);
you will then be able to get the file on the server with $_FILES["file"]

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

Categories

Resources