I am working on a file upload code which at the moment works only in Chrome and Firefox. It allows users to drag and drop files which get uploaded. The upload progress is shown in a grid.
Here is the html
<form id="fileUploadForm" action="home/upload" method="post" enctype="multipart/form-data">
<input type="file" id="fileselect" name="files" multiple="multiple" />
<div id="filedrag">Drop files here</div>
<button type="submit" id="submitbutton">Upload Files</button>
</form>
<table class="datatable" data-bind="visible:files().length>0">
<thead>
<tr>
<th>Name</th>
<th>Status</th>
<th>Upload progress</th>
<th>Progress bar</th>
</tr>
</thead>
<tbody data-bind="foreach:files">
<tr>
<td data-bind="text:name"></td>
<td data-bind="text:status"></td>
<td data-bind="text:percentUploaded"></td>
<td>
<progress max="100" data-bind="attr: {value:percentUploaded}"></progress>
<span data-bind="text:$root.files().length"></span></td>
</tr>
</tbody>
</table>
<pre data-bind="text: ko.toJSON($data.files, null, 2)"></pre>
And here is the JavaScript:
var File = function (f) {
this.name = f.name;
this.type = f.type;
this.size = f.size;
this.lastModified = f.lastModifiedDate.toDateString();
this.status = ko.observable(f.status);
this.percentUploaded = ko.observable(0);
};
var ViewModel = function () {
var self = this,
maxFileSize = 5000000,
onFileSelecting = function (e) {
e.stopPropagation();
e.preventDefault();
e.target.className = (e.type == "dragover" ? "hover" : "");
},
onFileSelected = function (e) {
onFileSelecting(e);// cancel event and hover styling
var files = e.target.files || e.dataTransfer.files;
for (var i = 0, f; f = files[i]; i++) {
var validationResult = validate(f);
f.status = validationResult || 'Uploading';
self.addFile(f);
uploadFile(f);
}
},
validate = function (f) {
if (f.size > maxFileSize)
return 'Too large, should be less than 5MB';
if (f.type.indexOf("text") != 0)
return 'Wrong file type';
},
uploadFile = function (f) {
var file = self.files()[0];
var fd = new FormData();
fd.append("files", f, f.name);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", function (e) {
file.status("Uploaded " + parseInt(e.loaded / e.total * 100) + "%");
file.percentUploaded(parseInt(e.loaded / e.total * 100));
}, false);
xhr.onreadystatechange = function (e) {
if (xhr.readyState == 4) {
file.status((xhr.status == 200 ? "success" : "failure"));
}
};
xhr.open("POST", $("#fileUploadForm")[0].action, true);
xhr.setRequestHeader("X_FILENAME", file.name);
xhr.send(fd);
};
self.files = ko.observableArray();
self.addFile = function (f) { self.files.unshift(new File(f)); };
$(document).ready(function () {
if (window.File && window.FileList && window.FileReader) {
var fileSelector = $("#fileselect"),
fileDragArea = $("#filedrag"),
submitButton = $("#submitbutton");
fileSelector.change(onFileSelected);
var xhr = new XMLHttpRequest();
if (xhr.upload) {
filedrag.addEventListener("dragover", onFileSelecting, false);
filedrag.addEventListener("dragleave", onFileSelecting, false);
filedrag.addEventListener("drop", onFileSelected, false);
filedrag.style.display = "block";
submitbutton.style.display = "none";
fileSelector.hide();
}
}
});
};
var model = new ViewModel();
ko.applyBindings(model);
When I drag and drop a set of files, everything works fine. However, when I drag and drop another set, the files array gets updated, but the grid does not show additional rows.
However, everything works fine when I take out this piece of HTML5 mark up:
<progress max="100" data-bind="attr: {value:percentUploaded}"></progress>
I have created the fiddle (http://jsfiddle.net/9aJtG/1) but it has other problems - 1) The drag and drop on fiddle just opens up the file (not sure why) 2) on dropping the files the files get submitted, but there is no server side code which can work with JSFiddle form posting
I have tried with progress bar in another example, which does not have this problem http://jsfiddle.net/bxfXd/800/
Any ideas?
Many thanks!
Related
How to get detail of user by clicking user id? I fetched the data from JSON API.But know i want some more functionality that I make a id as a link when user click on that link only this id of data will show from JSON API SERVER.I am wondering How this will happen using JS AJAX.Please help.
There is my code.
<html>
<body>
<table class = "src">
<tr><th>Name</th><th>id</th></tr>
<tr><td><div id = "Name"></div></td>
<td><div id = "Id"></div></td></tr>
</table>
</body>
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
var url = "https://jsonplaceholder.typicode.com/users";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(this.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
var name="";
var id="";
for(var i = 0; i < 10; i++) {
name += '' + jsonObj[i].name + ' <br>';
id+=jsonObj[i].id + '<br>' ;
}
document.getElementById("Name").innerHTML = name;
document.getElementById("Id").innerHTML = id;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
</script>
</html>
Target the id div and add click listener to them. Inside handler get the id using e.target.innerText
document.querySelectorAll("#tab div.userid").forEach(elem => elem.addEventListener("click", function(e) {
let xmlhttp = new XMLHttpRequest();
let url = `https://jsonplaceholder.typicode.com/users/${ e.target.innerText}`;
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
user = JSON.parse(this.responseText);
//handle your user data here
})
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
Following example finds the users in the array and displays its data.Here no request is made as data is already available in the array.
var users = [];
function getUsers() {
let xmlhttp = new XMLHttpRequest();
let url = "https://jsonplaceholder.typicode.com/users";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
users = JSON.parse(this.responseText);
let tableString = ` <tr> <th > Name </th> <th > id </th> </tr>`
users.forEach(obj => {
tableString += ` <tr>
<td>
<div class="name">${obj.name}</div>
</td>
<td>
<div class="userid">${obj.id}</div>
</td>
</tr>`
});
document.getElementById("tab").innerHTML = tableString;
document.querySelectorAll("#tab div.userid").forEach(elem => elem.addEventListener("click", function(e) {
getDataOfUser(e.target.innerText)
}))
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function getDataOfUser(id) {
let user = users.find(useR => useR.id == id);
document.querySelector(".info-user").innerHTML = `Info of user:
Name:${user.name}<br>
Email:${user.email}<br>
Phone:${user.phone}<br>
Website:${user.website}<br>
`
}
getUsers();
#tab td{
border:1px solid black
}
.userid{
cursor:pointer;
}
Click on id to get the user data
<table id="tab">
<table>
<div class="info-user">
</div>
I am working on a project and started using dropzone.js, and then was moved to another task, and when I returned to this task, a former co-worker had made some modifications..
Its prob an easy issue, but I am needing to learn - he created some TABLES which I dont want, I just want to be able to display the VAR data on items I create and control via css.
My issue, is I am lost on how to use his functions in the and make them be more "html" based so I can assign my css to it.
I´m trying dropzone.js and want the layout like on this page dropzonejs.com or this Work with DropzoneJS
<script>
var files = [];
var total_count = 0;
var processing = false;
function deleteFile(fileid) {
var file = files[fileid];
total_count -= file.count;
files[fileid] = null;
document.getElementById('dr_total').innerHTML = total_count;
var row = document.getElementById('dr_'+fileid);
row.parentNode.removeChild(row);
dz_deleteRemoteFile(file.file);
}
function checkout() {
if (processing) {
return true;
}
if (files.length < 1) {
alert('Please upload files');
return false;
}
processing = true;
document.getElementById('btnCheckout').innerHTML = 'Processing...';
var result = dz_addOrder();
if (!result) {
document.getElementById('btnCheckout').innerHTML = 'Checkout';
processing = false;
}
}
</script>
<script language="javascript" src="dropzone.js"></script>
<script>
Dropzone.options.myDropzone = {
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 200, // MB
//acceptedFiles: "application/csv,text/csv,application/vnd.ms-excel",
clickabke: false,
dictDefaultMessage: 'Drag or Select files to Upload',
method: "POST",
uploadMultiple: false,
accept: function(file, done) {
if (file.name.substring(file.name.length-3).toLowerCase() != 'csv') {
done('ERROR: Invalid file type, only CSV files allowed.');
} else {
done();
}
},
error: function(file, errorMessage, xhr) {
alert('ERROR: '+file.name+' '+errorMessage);
},
success: function(file, message) {
var ret = JSON.parse(message);
if (ret.status == "ERROR") {
alert('ERROR: '+file.name+' '+ret.message);
return false;
}
var obj = {
file:ret.file,
name:file.name,
count:ret.count
};
files.push(obj);
total_count += ret.count;
var table = document.getElementById('dr_files');
var row = table.insertRow(-1);
row.id = 'dr_'+(files.length-1);
row.insertCell(0).innerHTML = file.name;
row.insertCell(1).innerHTML = ret.count;
row.insertCell(2).innerHTML = '<button class="verifybuttonred" onclick="deleteFile('+(files.length-1)+')">delete</button>';
document.getElementById('dr_total').innerHTML = total_count;
var dz = this;
setTimeout(function(){
dz.removeFile(file);
},1000,dz);
}
};
</script>
<link rel="stylesheet" type="text/css" href="basic.css">
<link rel="stylesheet" type="text/css" href="dropzone.css">
<body>
<form action="data_hygiene/upload.php" id="myDropzone" class="dropzone" enctype="multipart/form-data" method="post">
<input type="hidden" name="clientid" id="clientid" value="0">
</form>
<div id="dr_filelist">
<br/><br/><br/><table border="1" cellpadding="5" cellspacing="5" bordercolor="#000000" width="100%" id="dr_files">
<tr><th width="70%">File</th><th width="15%">Count</th><th width="15%">Options</th></tr>
<tr><td></td><td></td><td></td></tr>
</table>
<table border="1" cellpadding="5" cellspacing="5" bordercolor="#000000" width="100%" id="dr_files">
<tr><th width="70%">Total</th><th width="15%"><div id="dr_total"></div></th><th width="15%"><button class="buttongreen" id="btnCheckout" onClick="checkout();">Checkout</button></th></tr>
</table>
So you will in near the end, he has the :
var table = document.getElementById('dr_files');
var row = table.insertRow(-1);
row.id = 'dr_'+(files.length-1);
row.insertCell(0).innerHTML = file.name;
row.insertCell(1).innerHTML = ret.count;
row.insertCell(2).innerHTML = '<button class="verifybuttonred" onclick="deleteFile('+(files.length-1)+')">delete</button>';
this is what I am wanting to remove from a TABLE layout...
This is how it currently looks - (which is crap)
enter image description here
Anyone can help me with my code? I wanna build an upload function using HTML5 API. if I upload less than 1mb the file is alright. However, if file more than 1mb the file will be corrupted.
the HTML file :
<!DOCTYPE html>
<html>
<head>
<title>Upload</title>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
</head>
<body>
<form method="POST" action="upload.php" enctype='multipart/form-data'>
<input type="file" name="fileToUpload" id="file"><br />
<input type="submit" id="submit">
</form>
</body>
<script>
$(document).ready(function(){
$('#submit').on('click', function(e){
e.preventDefault();
sendRequest();
});
//window.BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder;
var bytes_per_chunk = 1048576; // 1mb chunk sizes.
var global_upload_counter = 0;
function sendRequest(){
var blob = document.getElementById('file').files[0];
var total_size = blob.size;
var start = 0;
var end = bytes_per_chunk;
// var counter = 1;
while(start < total_size)
{
// console.log('start : ' + start + ', end :' + end + ' and counter : ', counter);
var chunk = blob.slice(start, end);
uploadFile(chunk, blob.name);
start = end;
end = start + bytes_per_chunk;
//counter++;
}
}
function uploadFile(chunk, filename){
var fd = new FormData();
fd.append('fileToUpload', chunk);
var xhr = new XMLHttpRequest();
xhr.addEventListener('load', uploadComplete, false);
xhr.addEventListener('error', uploadFailed, false);
xhr.addEventListener('abort', uploadCanceled, false);
xhr.open('POST', 'upload.php?filename=' + filename);
xhr.send(fd);
}
function uploadComplete(evt) {
// This event is raised when the server send back a response
if (evt.target.responseText != ""){
alert(evt.target.responseText);
}
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
}
function uploadCanceled(evt) {
xhr.abort();
xhr = null;
}
});
</script>
</html>
PHP code (upload.php):
<?php
$target_path = "upload/";
$tmp_name = $_FILES['fileToUpload']['tmp_name'];
$size = $_FILES['fileToUpload']['size'];
$name = $_FILES['fileToUpload']['name'];
$filename = $_GET['filename'];
//$target_file = $target_path.$name;
$complete = $target_path. $filename;
// append; open or create binary file for writing at end-of-file
$com = fopen($complete, "ab");
error_log($target_path);
// read as binary
$in = fopen($tmp_name, "rb");
if($in){
while ($buff = fread($in, $size)){
fwrite($com, $buff);
}
}
fclose($in);
First of all, why do you want to separate the file into chunks? You can upload the whole file in a go via AJAX. The error that you are encountering might be due to the chunk logic.
Try removing the chunk logic and it will work just fine. So your upload function would look something like this:
$(document).ready(function(){
$('#submit').on('click', function(e){
e.preventDefault();
sendRequest();
});
//window.BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder;
var bytes_per_chunk = 1048576; // 1mb chunk sizes.
var global_upload_counter = 0;
function sendRequest(){
var blob = document.getElementById('file').files[0];
var total_size = blob.size;
uploadFile(blob,filename);
}
function uploadFile(chunk, filename){
var fd = new FormData();
fd.append('fileToUpload', chunk);
var xhr = new XMLHttpRequest();
xhr.addEventListener('load', uploadComplete, false);
xhr.addEventListener('error', uploadFailed, false);
xhr.addEventListener('abort', uploadCanceled, false);
xhr.open('POST', 'upload.php?filename=' + filename);
xhr.send(fd);
}
function uploadComplete(evt) {
// This event is raised when the server send back a response
if (evt.target.responseText != ""){
alert(evt.target.responseText);
}
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
}
function uploadCanceled(evt) {
xhr.abort();
xhr = null;
}
});
Instead of chunks, send the full file and it should work.
If you are worried about the upload progress, here are a few solutions:
jQuery Upload Progress and AJAX file upload ,
File upload progress bar with jQuery
Looking at the answer provided by user470714 on uploading a file in chunks using html5 I found the issues.
Which the ajax didn't actually uploading the chunks in order. So I updated my HTML code as follow and now it works fine :
<!DOCTYPE html>
<html>
<head>
<title>Upload</title>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
</head>
<body>
<form method="POST" action="upload.php" enctype='multipart/form-data'>
<input type="file" name="fileToUpload" id="file"><br />
<input type="submit" id="submit">
</form>
</body>
<script>
$(document).ready(function(){
$('#submit').on('click', function(e){
e.preventDefault();
sendRequest();
});
//window.BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder;
var bytes_per_chunk = 1048576; // 1mb chunk sizes.
var global_upload_counter = 0;
function sendRequest(){
var blob = document.getElementById('file').files[0];
var total_size = blob.size;
window.upload_counter = 0;
window.upload_filearray = [];
var start = 0;
var end = bytes_per_chunk;
while(start < total_size)
{
var chunk = blob.slice(start, end);
window.upload_filearray[window.upload_counter] = chunk;
window.upload_counter++;
start = end;
end = start + bytes_per_chunk;
}
// initiate upload the first time
window.upload_counter = 0;
window.filename = blob.name;
uploadFile(window.upload_filearray[window.upload_counter]);
}
function uploadFile(chunk){
var fd = new FormData();
fd.append('fileToUpload', chunk);
var xhr = new XMLHttpRequest();
xhr.addEventListener('load', uploadComplete, false);
xhr.addEventListener('error', uploadFailed, false);
xhr.addEventListener('abort', uploadCanceled, false);
xhr.open('POST', 'upload.php?filename=' + window.filename);
window.upload_counter++;
xhr.send(fd);
}
function uploadComplete(evt) {
// This event is raised when the server send back a response
if (evt.target.responseText != ""){
console.log(evt.target.responseText);
}
if(window.upload_filearray.length > window.upload_counter){
uploadFile(window.upload_filearray[window.upload_counter]);
}
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
}
function uploadCanceled(evt) {
xhr.abort();
xhr = null;
}
});
</script>
</html>
My html 5 canvas is being saved to a server via php. It also pops up in a new window that is not html. The new window only contains the png image. I would like this new popup window to be able to share to social media. I know about auth2.0 and setting that up. What I don't know is how to get my png created from the saved canvas to popup on a new html page so I can add my social media tools. I am pretty sure it would be an edit to this line, window.open(testCanvas.toDataURL("images/png"));.
function saveImage() {
cursor.visible = false; stage.update();
var canvasData = testCanvas.toDataURL("image/png");
window.open(testCanvas.toDataURL("images/png"));
var xmlHttpReq = false;
if (window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
cursor.visible = true; stage.update();
}
else if (window.ActiveXObject) {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
ajax.open('POST', 'testSave.php', false);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajax.onreadystatechange = function() {
console.log(ajax.responseText);
}
ajax.send("imgData="+canvasData);
}
New example without server side (using localStorage)
On the first page:
<input type="file" id="upfile" />
<script>
$ = function(id) { return document.getElementById(id); };
$('upfile').onchange = function(e) {
var files = e.target.files;
for (var i = 0; i < files.length; i++)
{
var f = files[i];
if (! f.type.match('image.*'))
continue;
var reader = new FileReader();
reader.onload = (function(filecontent) {
return function(ev) {
var b64data = ev.target.result;
localStorage.setItem('img', b64data);
window.open('popup.html', 'popup', 'width=600,height=400');
};
})(f);
reader.readAsDataURL(f);
}
};
</script>
In the popup page:
<img src="" id="thepicture" />
<script>
window.onload = function() {
document.getElementById('thepicture').src = localStorage.getItem('img');
};
</script>
Check the working demo here
I have been working on the following paradigm, in order to learn "how to drag an image from my desktop and drop it in my browser" works with Html 5. But after I drop the image, I just can't get the information about the image's actual width and height in the function handleFiles(files,n) where I alert it. Is this even possible?
Can anyone help me?
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:og="http://ogp.me/ns#"
xmlns:fb="http://www.facebook.com/2008/fbml" xml:lang="el-gr" lang="el-gr" dir="ltr">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Files javascript upload with drag and drop</title>
</head>
<title>File(s) size</title>
</head>
<body>
<table>
<tr>
<td><input type="file" id="fileElem1" name="fileElem1" accept="image/*" style="display:none" onchange="handleFiles(this.files)">
<div id="dropbox_1" style="width:200px;height:100px;border:1px solid blue;z-index=10;">
<div id="preview1"></div>
</div>
</td>
<td><input type="file" id="fileElem2" name="fileElem2" accept="image/*" style="display:none" onchange="handleFiles(this.files)">
<div id="dropbox_2" style="width:200px;height:100px;border:1px solid blue;"> <div id="preview2"></div></div></td>
<td><input type="file" id="fileElem3" name="fileElem3" accept="image/*" style="display:none" onchange="handleFiles(this.files)">
<div id="dropbox_3" style="width:200px;height:100px;border:1px solid blue;"> <div id="preview3"></div></div></td>
</tr>
</table>
<input type="button" onclick="sendFiles()" value="send" >
<script>
var dropbox1,dropbox2,dropbox3;
dropbox1 = document.getElementById("dropbox_1");
dropbox1.addEventListener("dragenter", dragenter, false);
dropbox1.addEventListener("dragover", dragover, false);
dropbox1.addEventListener("drop", drop, false);
dropbox2 = document.getElementById("dropbox_2");
dropbox2.addEventListener("dragenter", dragenter, false);
dropbox2.addEventListener("dragover", dragover, false);
dropbox2.addEventListener("drop", drop, false);
dropbox3 = document.getElementById("dropbox_3");
dropbox3.addEventListener("dragenter", dragenter, false);
dropbox3.addEventListener("dragover", dragover, false);
dropbox3.addEventListener("drop", drop, false);
var fileElem1 = document.getElementById("fileElem1");
var fileElem2 = document.getElementById("fileElem2");
var fileElem3 = document.getElementById("fileElem3");
function dragenter(e) {
e.stopPropagation();
e.preventDefault();
}
function dragover(e) {
e.stopPropagation();
e.preventDefault();
}
function drop(e) {
e.stopPropagation();
e.preventDefault();
var n=e.currentTarget.id.split("_");
var dt = e.dataTransfer;
var files = dt.files;
handleFiles(files,n[1]);
}
var filesforupload = new Array(null,null,null);
function handleFiles(files,n) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var img = document.createElement("img");
img.classList.add("obj");
img.file = file;
alert(img.width); // <- HERE I NEED TO GET THE width of the image
img.style.zIndex=2;
img.style.position="absolute";
document.getElementById("dropbox_"+n).style.height="200";
document.getElementById("preview"+n).innerHTML = "";
document.getElementById("preview"+n).appendChild(img);
var reader = new FileReader();
reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
reader.readAsDataURL(file);
filesforupload[n-1]=file;
//filesforupload.push(file);
//sendFile(file);
}
}
function sendFile(file) {
var uri = "upload.php";
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.open("POST", uri, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// Handle response.
alert(xhr.responseText);
// handle response.
}
};
var reader = new FileReader();
fd.append('fileElem', file);
// Initiate a multipart/form-data upload
xhr.send(fd);
}
function sendFiles(){
for (var i=0; i<filesforupload.length; i++) {
if(filesforupload[i]!=null)
sendFile(filesforupload[i]);
}
}
dropbox1.ondrop = function(event) {
event.stopPropagation();
event.preventDefault();
filesArray = event.dataTransfer.files;
}
function dump(obj) {
var out = '';
for (var i in obj) {
out += i + ": " + obj[i] + "\n";
}
alert(out);
}
</script>
</body>
</html>
Try it this way (updated with 100 ms timeout):
reader.onload = (function(aImg) {
return function(e) {
aImg.src = e.target.result;
setTimeout(function() {
console.log(aImg.width); // right now file already loaded...
}, 100);
};
})(img);
http://jsfiddle.net/wVB3V/3/
anyway I found the following solution by adding an id to the image + onload function on the image like this
img.addEventListener('load', function() { alert(document.getElementById('test').width); /* ... */ }, false);
img.id="test";
The order does not matter since the load event fires after the img object gets appended.
Here is the complete code.
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:og="http://ogp.me/ns#"
xmlns:fb="http://www.facebook.com/2008/fbml" xml:lang="el-gr" lang="el-gr" dir="ltr">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>File(s) javascript upload with drag and drop</title>
</head>
<title>File(s) size</title>
</head>
<body>
<table>
<tr>
<td><input type="file" id="fileElem1" name="fileElem1" accept="image/*" style="display:none" onchange="handleFiles(this.files)">
<div id="dropbox_1" style="min-width:200px;height:100px;border:1px solid blue;z-index=10;">
<div id="preview1"></div>
</div>
</td>
<td><input type="file" id="fileElem2" name="fileElem2" accept="image/*" style="display:none" onchange="handleFiles(this.files)">
<div id="dropbox_2" style="width:200px;height:100px;border:1px solid blue;"> <div id="preview2"></div></div></td>
<td><input type="file" id="fileElem3" name="fileElem3" accept="image/*" style="display:none" onchange="handleFiles(this.files)">
<div id="dropbox_3" style="width:200px;height:100px;border:1px solid blue;"> <div id="preview3"></div></div></td>
</tr>
</table>
<input type="button" onclick="getthewidth()" value="send" >
<script>
function getthewidth(){
alert(document.getElementById('test').width);
}
var dropbox1,dropbox2,dropbox3;
dropbox1 = document.getElementById("dropbox_1");
dropbox1.addEventListener("dragenter", dragenter, false);
dropbox1.addEventListener("dragover", dragover, false);
dropbox1.addEventListener("drop", drop, false);
dropbox2 = document.getElementById("dropbox_2");
dropbox2.addEventListener("dragenter", dragenter, false);
dropbox2.addEventListener("dragover", dragover, false);
dropbox2.addEventListener("drop", drop, false);
dropbox3 = document.getElementById("dropbox_3");
dropbox3.addEventListener("dragenter", dragenter, false);
dropbox3.addEventListener("dragover", dragover, false);
dropbox3.addEventListener("drop", drop, false);
var fileElem1 = document.getElementById("fileElem1");
var fileElem2 = document.getElementById("fileElem2");
var fileElem3 = document.getElementById("fileElem3");
function dragenter(e) {
e.stopPropagation();
e.preventDefault();
}
function dragover(e) {
e.stopPropagation();
e.preventDefault();
}
function drop(e) {
e.stopPropagation();
e.preventDefault();
var n=e.currentTarget.id.split("_");
var dt = e.dataTransfer;
var files = dt.files;
handleFiles(files,n[1]);
}
var filesforupload = new Array(null,null,null);
function handleFiles(files,n) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var img = document.createElement("img");
img.classList.add("obj");
img.file = file;
img.addEventListener('load', function() { alert(document.getElementById('test').width); /* ... */ }, false);
img.id="test";
//alert(document.getElementById('test').id);
// alert(img.width); // <- HERE I NEED TO GET THE width of the image
img.style.zIndex=2;
img.style.position="absolute";
//document.getElementById("dropbox_"+n).style.height="200";
document.getElementById("preview"+n).innerHTML = "";
document.getElementById("preview"+n).appendChild(img);
var reader = new FileReader();
reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
reader.readAsDataURL(file);
filesforupload[n-1]=file;
//filesforupload.push(file);
//sendFile(file);
}
}
function sendFile(file) {
var uri = "upload.php";
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.open("POST", uri, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// Handle response.
alert(xhr.responseText);
// handle response.
}
};
var reader = new FileReader();
fd.append('fileElem', file);
// Initiate a multipart/form-data upload
xhr.send(fd);
}
function sendFiles(){
for (var i=0; i<filesforupload.length; i++) {
if(filesforupload[i]!=null)
sendFile(filesforupload[i]);
}
}
dropbox1.ondrop = function(event) {
event.stopPropagation();
event.preventDefault();
filesArray = event.dataTransfer.files;
}
function dump(obj) {
var out = '';
for (var i in obj) {
out += i + ": " + obj[i] + "\n";
}
alert(out);
}
</script>
</body>
</html>