Multiple File Upload in codeigniter using HTML5 and XHR - html

I'm working on multifile upload using html5 and xhr, as you can see I'm sending requests in loop which is a bad
concept but I'm not able to upload files when I send it outside the loop and only the last file gets upoaded.
Where am I going wrong?
$('#uploadimg').on('click', function(e) {
var files = document.getElementById('files').files;
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
formData.append('file', files[i]);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost/ajaxuploader/upload/uploadimg');
xhr.onload = function() {
if (xhr.status === 200) {
console.log('all done: ' + xhr.status);
} else {
console.log('Something went terribly wrong...');
}
};
xhr.send(formData);
}
// now post a new XHR request
});
Codeigniter
public function uploadimg (){
$config['upload_path'] = FCPATH . 'uploads/' ;
$config['allowed_types'] = 'gif|jpg|png|jpeg|pdf|doc';
$config['remove_spaces'] = 'TRUE';
$this -> load -> library('upload', $config);
//$this->upload->initialize($config);
foreach ($_FILES as $k => $f) :
$this -> upload -> do_upload($k);
endforeach;
//$this->index();
}

Its seems the first thing you should look at is your js for loop. ID's should be unique so I would rule that approach out.
I would maybe loop each input field, check to see if the attr type == file, then append that to your formData object.
var inpts = document.getElementsByTagName('input');
for(var i=0; i < inpts.length; i++)
{
if(inpts[i].getAttribute('type') == 'file')
{
formData.append('myFiles[]', inpts[i].files[0]);
}
}
On the server side I would look at your foreach loop, maybe a for loop might suffice.
for($i=0; $i < count($_FILES); $i++){
$this->upload->initialize(); //new initialization for each file
$this->upload->do_upload($_FILES[$i]);
continue;
};

Hi guys i figured out the problem codeigniter is working fine, the problem is in the jquery. this is the line causing the problem. "formData.append(files[i].name, files[i]);" Thanks for all for takign efforts to solve my issue
$('#uploadimg').on('click', function(e) {
//console.log(files);
// files = document.getElementById('files').files;
var formData = new FormData();
$(files).each(function(i) {
formData.append(files[i].name, files[i]);
})
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost/ajaxuploader/upload/uploadimg');
xhr.onload = function(data) {
console.log(xhr.responseText);
};
xhr.send(formData);
});

Related

XMLHttpRequest ERROR in QML Blackberry 10

I'm trying to get movie data for BlackBerry 10 apps.
I don't know where I'm making a mistake.
Please, can you help me?
Thank you all.
import bb.cascades 1.4
Page {
onCreationCompleted: {
sendRequest();
}
function sendRequest() {
var data = "{}";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://api.themoviedb.org/3/search/movie?include_adult=false&page=1&query=hulk&language=en-US&api_key=YOUR_API_KEY_HERE");
xhr.send(data);
}
}
You need to use the onreadystatechange EventHandler.
Also, you don't need to pass data when making a GET request.
I have removed the withCredentials line as it isn't needed in this example.
You can learn more on XMLHttpRequest here :
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
onCreationCompleted: {
sendRequest();
}
function sendRequest() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
var json = JSON.parse(xhr.responseText);
var results = json.results;
var count = results.length;
console.log("There are " + count + " results :");
json.results.forEach((value, index) =>
{
console.log(index + " - " + value.title);
});
}
};
xhr.open("GET", "https://api.themoviedb.org/3/search/movie?include_adult=false&page=1&query=hulk&language=en-US&api_key=YOUR_API_KEY_HERE");
xhr.send();
}
Here's an example of using XMLHttpRequest I've made a long time ago :
https://github.com/RodgerLeblanc/Markup/blob/master/assets/main.qml

html <script> tag headers

I'm trying to require a script that is firewalled with a header authentication system and trying to find a way around it.
So far it's pretty evident that you can't add custom headers to the script tag its self but I have seen something about customizing the headers on the page before requesting or on the server side.
Until this point, I can't say I've seen any solid answers.
You can load it via xhr and eval() it in-page. For example with jQuery, you can use:
http://api.jquery.com/jquery.ajax/ - see beforeSend to set headers; use this to retrieve the file content.
Then use https://api.jquery.com/jquery.globaleval/ globalEval() to eval the gotten content in-page.
You could achieve the same with vanilla HttpRequest and eval(), but I was always too lazy to do it that way. Or maybe not... I just found a piece of code in the project I'm working:
var evalScript = function(e) {
var h = evalScript.node,
s = document.createElement("script");
s.type = "text/javascript";
s.text = e;
h.appendChild(s);
h.removeChild(s);
};
evalScript.node = document.getElementsByTagName("head")[0] || document.getElementsByTagName("*")[0];
// TODO: make async
function loadJs(js) {
var req = new XMLHttpRequest();
req.open("GET", js, false);
req.send(null);
evalScript(req.responseText);
}
Just add the headers to this.
Here's a simple Ajax function you could use to get the contents of the script:
function get(url, callback) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.onreadystatechange = function() {
if(this.readyState === 4) {
if(this.status >= 200 && this.status < 400) {
callback.apply(this, [this.responseText, this]);
} else {
// something went wrong.
}
}
};
request.send();
}
Since you need to set custom headers, you'd also use the request.setRequestHeader method, like this:
function get(url, callback) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
// BEGIN: CUSTOM HEADERS
request.setRequestHeader("Header-Name", "header/value");
request.setRequestHeader("Other-Header", "other/value");
// END: CUSTOM HEADERS
request.onreadystatechange = function() {
if(this.readyState === 4) {
if(this.status >= 200 && this.status < 400) {
callback.apply(this, [this.responseText, this]);
} else {
// something went wrong.
}
}
};
request.send();
}
And finally, you'd use the function, like this:
get("url/to/your/script", function(response) {
// perform checks...
window.eval(response);
});
WARNING: be very, VERY careful when using eval, don't ever eval something you don't trust and remember eval can be evil.

How convert JSON data to html table

I get real-time statistics for myself and the data in JSON format. The problem is, I can not figure how can I get this table in html web page.
Data can be found at: http://testinki.info/apidata/
I have tried something like this, but without success:
<!DOCTYPE html>
<html>
<body>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://testinki.info/apidata/";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].apikey +
"</td></tr>"
}
out += "</table>"
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
Any ideas? How to solve the problem?
AngularJS might be a good solution for the task. With data from your link, code will look something like this:
Api key: {{data.apikey}}
<br>
User:
<pre>{{data.data|json}}</pre>
<br>
<table>
<tr ng-repeat="member in data.Members">
<td>{{member.name}}</td>
<td>{{member.info}}</td>
</tr>
</table>
angular
.module("app", [])
.controller("ctrl", function ($http, $scope, $http) {
$http
.get("http://testinki.info/apidata/")
.then(function (res) {
$scope.data = res;
})
})
JSBin example. I've changed $http to $timeout and predefined data since your API does not allow cross-origin requests.

Fileupload using Filereader in chrome

I have to upload a file from the local memory of application (HTML5 File api). Onselect, the user should be able to upload directly without any question. The idea is to manage download/upload seamless to the user. Here is the code :
$("body").on("click", ".upload-file", function(e){
var fileToUpload = $('input:radio[name=optionsRadios]:checked').val();
var formData = new FormData();
$('input:radio[name=optionsRadios]:checked').parent().parent().parent().remove();
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.TEMPORARY, 50*1024*1024, initFS, errorHandler);
var reader = new FileReader();
function initFS(fs){
fs.root.getDirectory('/', {}, function(dirEntry){
var dirReader = dirEntry.createReader();
dirReader.readEntries(function(entries) {
for(var key = 0; key < entries.length; key++) {
var entry = entries[key];
if (entry.isFile){
var name = entry.name;
if(name == fileToUpload){
getAsText(entry.toURL());
formData.append('file', entry.toURL);
break;
}
}
}
}, errorHandler);
}, errorHandler);
}
function errorHandler(){
console.log('An error occured');
}
function getAsText(readFile) {
alert ("getting as text :" +readFile);
var reader = new FileReader();
// Read file into memory as UTF-16
reader.readAsText(readFile, "UTF-16");
// Handle progress, success, and errors
reader.onprogress = updateProgress;
reader.onload = loaded;
reader.onerror = errorHandler;
}
function loaded(evt) {
// Obtain the read file data
alert("loaded file");
var fileString = evt.target.result;
// Handle UTF-16 file dump
if(utils.regexp.isChinese(fileString)) {
//Chinese Characters + Name validation
}
else {
// run other charset test
}
// xhr.send(fileString)
}
var serverurl = "/fileserver/uploadFile?selpath="+fileToUpload;
var xhr = new XMLHttpRequest();
xhr.open('POST', serverurl);
xhr.onload = function () {
if (xhr.status === 200) {
console.log('all done: ' + xhr.status);
} else {
console.log('Something went terribly wrong...');
}
};
xhr.send(formData);
});
Now, I am trying to read the file as text (its a bad practice but wanted to find someway to make it work) but it doesn't throw any events. Can you please help me to find where I am going wrong ?

In html5 server sent event, why do I see polling log on fiddler

I am not able to figure out that why do I see polling log in fiddler for the server sent event I am trying to implement using HTML 5. Please find the image of my fiddler log below
If its server sent event, the message should be sent from server without system calling the method again and again to look for updates. Or i have not implemented it properly. Here my code:
<script type="text/javascript">
$(function () {
var userStatusChangeEvent = new EventSource("/events");
userStatusChangeEvent.onmessage = function (event) {
data = $.parseJSON(event.data);
for (index = 0; index < data.length; index++) {
$elem = $('#' + data[index].Id);
isOnline = data[index].IsOnline;
if (isOnline) {
$elem.addClass('is_online');
$('.loginTimestamp', $elem).html(data[index].Time);
}
else {
$elem.removeClass('is_online');
$('.loginTimestamp', $elem).html('');
}
}
};
});
</script>
public virtual ActionResult Events()
{
var userStream = new UserServerSentStatusResult();
userStream.ChangeUserStatus = new LoggedUsersViewModel().Users.Where(x => x.HasChanged).ToList();
userStream.Content = () =>
{
var serializer = new JavaScriptSerializer();
return serializer.Serialize(userStream.ChangeUserStatus);
};
userStream.ChangeUserStatus.ForEach(x =>
{
x.HasChanged = false;
x.Time = DateTime.Now.ToShortTimeString();
});
return userStream;
}
Turn on the Streaming mode in Fiddler