Javascript Drag and Drop Files, then Sort - javascript

I am trying to Sort files I pull from File Explorer by name, they sort by when they load, how would I sort them by name instead using my code below?
(function() {
// getElementById
function $id(id) {
return document.getElementById(id);
}
// output information
function Output(msg) {
var m = $id("messages");
m.innerHTML = msg + m.innerHTML;
}
// file drag hover
function FileDragHover(e) {
e.stopPropagation();
e.preventDefault();
e.target.className = (e.type == "dragover" ? "hover" : "");
}
// file selection
function FileSelectHandler(e) {
// cancel event and hover styling
FileDragHover(e);
// fetch FileList object
var files = e.target.files || e.dataTransfer.files;
// process all File objects
for (var i = 0, f; f = files[i]; i++) {
ParseFile(f);
}
}
// output file information
function ParseFile(file) {
// display an image
if (file.type.indexOf("image") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
Output(
"<p align=center><strong>" + file.name + ":</strong><br />" +
'<img src="' + e.target.result + '"></p>'
);
}
reader.readAsDataURL(file);
}
// display text
if (file.type.indexOf("text") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
Output(
"<p><strong>" + file.name + ":</strong></p><pre>" +
e.target.result.replace(/</g, "<").replace(/>/g, ">") +
"</pre>"
);
}
reader.readAsText(file);
}
}
// initialize
function Init() {
var fileselect = $id("fileselect"),
filedrag = $id("filedrag"),
submitbutton = $id("submitbutton");
// file select
fileselect.addEventListener("change", FileSelectHandler, false);
// is XHR2 available?
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// file drop
filedrag.addEventListener("dragover", FileDragHover, false);
filedrag.addEventListener("dragleave", FileDragHover, false);
filedrag.addEventListener("drop", FileSelectHandler, false);
filedrag.style.display = "block";
// remove submit button
submitbutton.style.display = "none";
}
}
// call initialization file
if (window.File && window.FileList && window.FileReader) {
Init();
}
})();
This code drags and drops the Files in my program and loads them, but does not sort in alphabetical, what would be the best way to sort them with my code below?

var files;
(function() {
// getElementById
function $id(id) {
return document.getElementById(id);
}
// output information
function Output(msg) {
var m = $id("messages");
m.innerHTML = msg + m.innerHTML;
}
// file drag hover
function FileDragHover(e) {
e.stopPropagation();
e.preventDefault();
e.target.className = (e.type == "dragover" ? "hover" : "");
}
// file selection
function FileSelectHandler(e) {
// cancel event and hover styling
FileDragHover(e);
// fetch FileList object
var files = e.target.files || e.dataTransfer.files;
// process all File objects
for (var i = 0, f; f = files[i]; i++) {
ParseFile(f);
}
}
// output file information
function ParseFile(file) {
// display an image
var basename = file.name.substring(0,file.name.length-4);
files.push("<div style=\"width: 100%; overflow: hidden;\"><div style=\"width: 600px; float: left;\">" +
"<strong>" + basename + ".pdf:</strong><br />" +
'<iframe src="\\\\sovarchpri01\\d$\\1000Sunrise\\Process\\stage\\' + basename +".pdf#view=fit" + '"height="75%" width="500px"></iframe></p>' +
"</div><div style=\"margin-left: 620px;\">" +
"<strong>" + basename + ".png:</strong><br />" +
"<img src=\"\\\\sovarchpri01\\d$\\Fleissner\\ORG_5535_Documents\\" + basename + ".png\" height=\"75%\" width=\"500px\">" +
"</div> ");
}
function sortFiles() {
files.sort().reverse();
for (var i = 0; i < files.length; ++i) {
Output(files[i]);
}
}
function resetWindow(){
window.location.reload(true)
}
// initialize
function Init() {
var fileselect = $id("fileselect"),
filedrag = $id("filedrag"),
submitbutton = $id("submitbutton"),
sortbutton = $id("sortbutton"),
resetbutton = $id("resetbutton")
resetbutton2 = $id("resetbutton2");;
files = new Array();
// file select
fileselect.addEventListener("change", FileSelectHandler, false);
// is XHR2 available?
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// file drop
filedrag.addEventListener("dragover", FileDragHover, false);
filedrag.addEventListener("dragleave", FileDragHover, false);
filedrag.addEventListener("drop", FileSelectHandler, false);
filedrag.style.display = "block";
// remove submit button
submitbutton.addEventListener("click", sortFiles , false); //style.display = "none";
sortbutton.addEventListener("click", sortFiles , false);
resetbutton.addEventListener("click", resetWindow , false);
resetbutton2.addEventListener("click", resetWindow , false);
}
}
// call initialization file
if (window.FileReader) {
Init();
}
})();

Related

Dropzone Js get file data (csv. xlsx) before Uploading

I'm new to Dropzone Js and i want to upload a file, process data to json then upload to my Flask server.
i appreciate any kind of help, thanks.
var id = '#kt_dropzone_4';
// set the preview element template
var previewNode = $(id + " .dropzone-item");
previewNode.id = "";
var previewTemplate = previewNode.parent('.dropzone-items').html();
previewNode.remove();
var myDropzone4 = new Dropzone(id, { // Make the whole body a dropzone
url: "/Upload", // Set the url for your upload script location
headers: {
'x-csrftoken': $('#csrf_Upload').val()
},
method: "post",
parallelUploads: 5,
acceptedFiles: ".xls, .xlsx, .csv",
previewTemplate: previewTemplate,
maxFilesize: 2, // Max filesize in MB
autoQueue: false, // Make sure the files aren't queued until manually added
previewsContainer: id + " .dropzone-items", // Define the container to display the previews
clickable: id +
" .dropzone-select" // Define the element that should be used as click trigger to select files.
});
myDropzone4.on("addedfile", function (file) {
// Hookup the start button
file.previewElement.querySelector(id + " .dropzone-start").onclick = function () {
myDropzone4.enqueueFile(file);
};
$(document).find(id + ' .dropzone-item').css('display', '');
$(id + " .dropzone-upload, " + id + " .dropzone-remove-all").css('display', 'inline-block');
//remove duplicates
if (this.files.length) {
var i, len;
for (i = 0, len = this.files.length; i < len - 1; i++) // -1 to exclude current file
{
if (this.files[i].name === file.name && this.files[i].size === file.size && this.files[i]
.lastModifiedDate.toString() === file.lastModifiedDate.toString()) {
this.removeFile(file);
$('#muted-span').text('Duplicates are not allowed').attr('class', 'kt-font-danger kt-font-bold').hide()
.fadeIn(1000)
setTimeout(function () {
$('#muted-span').hide().text('Only Excel and csv files are allowed for upload')
.removeClass('kt-font-danger kt-font-bold').fadeIn(500);
}, 2500);
}
}
}
});
// Update the total progress bar
myDropzone4.on("totaluploadprogress", function (progress) {
$(this).find(id + " .progress-bar").css('width', progress + "%");
});
myDropzone4.on("sending", function (file, response) {
console.log(file)
console.log(response)
// Show the total progress bar when upload starts
$(id + " .progress-bar").css('opacity', '1');
// And disable the start button
file.previewElement.querySelector(id + " .dropzone-start").setAttribute("disabled", "disabled");
});
// Hide the total progress bar when nothing's uploading anymore
myDropzone4.on("complete", function (progress) {
var thisProgressBar = id + " .dz-complete";
setTimeout(function () {
$(thisProgressBar + " .progress-bar, " + thisProgressBar + " .progress, " + thisProgressBar +
" .dropzone-start").css('opacity', '0');
}, 300)
});
// Setup the buttons for all transfers
document.querySelector(id + " .dropzone-upload").onclick = function () {
myDropzone4.enqueueFiles(myDropzone4.getFilesWithStatus(Dropzone.ADDED));
};
// Setup the button for remove all files
document.querySelector(id + " .dropzone-remove-all").onclick = function () {
$(id + " .dropzone-upload, " + id + " .dropzone-remove-all").css('display', 'none');
myDropzone4.removeAllFiles(true);
};
// On all files completed upload
myDropzone4.on("queuecomplete", function (progress) {
$(id + " .dropzone-upload").css('display', 'none');
});
// On all files removed
myDropzone4.on("removedfile", function (file) {
if (myDropzone4.files.length < 1) {
$(id + " .dropzone-upload, " + id + " .dropzone-remove-all").css('display', 'none');
}
});
I have not found yet a way to get the uploaded data from dropzonejs. I tried to read the file with FileReader but it's not a binary data (correct me if i'm wrong).
I need to process data on myDropzone4.on("addedfile", function (file){})
and return it as a json format if possible.
I found an answer for it, I just needed to find the input type file.when using dropzone.js either you find the input type file in the html page or in their javascript file, where i found that the input type file was being created with a class to hide this element :
var setupHiddenFileInput = function setupHiddenFileInput() {
if (_this3.hiddenFileInput) {
_this3.hiddenFileInput.parentNode.removeChild(_this3.hiddenFileInput);
}
_this3.hiddenFileInput = document.createElement("input");
_this3.hiddenFileInput.setAttribute("type", "file");
_this3.hiddenFileInput.setAttribute("id", "123");
if (_this3.options.maxFiles === null || _this3.options.maxFiles > 1) {
_this3.hiddenFileInput.setAttribute("multiple", "multiple");
}
// _this3.hiddenFileInput.className = "dz-hidden-input";
}
so i gave it an id and bind an event to the input then i read the file with two functions depends on the format of the file uploaded, for csv files to json :
function getText(fileToRead) {
var reader = new FileReader();
reader.readAsText(fileToRead);
reader.onload = loadHandler;
reader.onerror = errorHandler;
}
function loadHandler(event) {
var csv = event.target.result;
process(csv);
}
function process(csv) {
// Newline split
var lines = csv.split("\n");
result = [];
var headers = lines[0].split(",");
for (var i = 1; i < lines.length - 1; i++) {
var obj = {};
//Comma split
var currentline = lines[i].split(",");
for (var j = 0; j < headers.length; j++) {
obj[headers[j]] = currentline[j];
}
result.push(obj);
}
console.log(result);
}
function errorHandler(evt) {
if (evt.target.error.name == "NotReadableError") {
alert("Canno't read file !");
}
}
Read excel files (xls,xlsx) format to json format:
var ExcelToJSON = function () {
this.parseExcel = function (file) {
var reader = new FileReader();
reader.onload = function (e) {
var data = e.target.result;
var workbook = XLSX.read(data, {
type: 'binary'
});
workbook.SheetNames.forEach(function (sheetName) {
// Here is your object
var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[
sheetName]);
var json_object = JSON.stringify(XL_row_object);
console.log(JSON.parse(json_object));
jQuery('#xlx_json').val(json_object);
})
};
reader.onerror = function (ex) {
console.log(ex);
};
reader.readAsBinaryString(file);
};
};
the event that will detect change on the input, detect file format then use one of those to get the result in a JSON format:
$(document).ready(function () {
$('input[type="file"]').on('change', function (e) {
// EXCEL TO JSON
var files = e.target.files;
console.log(files)
var xl2json = new ExcelToJSON();
xl2json.parseExcel(files[0]);
var fileName = e.target.files[0].name;
console.log('The file "' + fileName + '" has been selected.');
// CSV TO JSON
var files = e.target.files;
if (window.FileReader) {
getText(files[0]);
} else {
alert('FileReader are not supported in this browser.');
}
});
});
I hope this helps i'm using dropzonejs with keenthemes implementation.

Multiple files upload with ajax

I'm trying to make a script to upload multiple files using ajax, and print them on the screen with a loading circle display.
The script is working for one file, but I have a problem to make it works for multiple files. I guess it a "scope" problem. But my JS knowledge is not that good.
Also, I'm only using standard JS, no jQuery.
Here's the script :
var index_div = 0;
var dropper = document.querySelector('#upload');
dropper.addEventListener('dragover', function(e) {
e.preventDefault(); // Annule l'interdiction de "drop"
}, false);
dropper.addEventListener('dragenter', function() {
dropper.style.borderStyle = 'solid';
});
dropper.addEventListener('dragleave', function() {
dropper.style.borderStyle = 'dashed';
});
dropper.addEventListener('drop', function(e) {
e.preventDefault();
dropper.style.borderStyle = 'dashed';
var files = e.dataTransfer.files,
filesLen = files.length;
for (var i = 0 ; i < filesLen ; i++) {
var NomImage = files[i].name;
if(files[i] != '')
{
if(window.XMLHttpRequest)
{
xhr=new XMLHttpRequest();
}
    else if(window.ActiveXObject)
{
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
var newDiv = document.createElement("div");
newDiv.setAttribute("class","image_div");
document.getElementById("upload").appendChild(newDiv);
document.getElementsByClassName("image_div")[index_div].innerHTML = '<img id="chargement" src="../includes/chargement.gif"/>';
    var form = new FormData();
    form.append('file', files[i]);
xhr.open('POST', "./traitement_upload.php", true);
xhr.onload = function (e) {
if(xhr.readyState==4 && xhr.status==200)
{
      document.getElementsByClassName("image_div")[index_div].innerHTML =
xhr.responseText;
index_div += 1;
    }
}
    xhr.send(form);
}
}
});
Sorry for the sloppy code. If I check the xhr readyState and status during the loop, the first(s) are 1 and 0, then the last one is good.
You can see I'm creating a new div for each uploaded file so I can print a thumbnail in it.
For what I understand, the code is processing while the ajax request is not done yet. The result is I only see the last file I submitted.
If I put a false to the async flag on xhr.open, it works but it doesn't show the loading gif of course.
Thank you for your help.
You should extract the code for AJAX functionality in a separate function - otherwise the closure for xhr.onload will use the current (at the time of calling) value of index_div - most probably the last one from the FOR cycle. Also, querySelector returns a collection - even if it finds just a single element, or even if it finds nothing. Also, you should use both event.dataTransfer and event.target in order to handle both drag/drop and normal clicking.
var dropper = document.getElementById('upload');
dropper.addEventListener('dragover', function(e)
{
e.preventDefault();
dropper.style.background = '#eee';
}, false);
dropper.addEventListener('dragenter', function()
{
e.preventDefault();
dropper.style.background = '#eee';
}, false);
dropper.addEventListener('dragleave', function()
{
e.preventDefault();
dropper.style.background = '#fff';
}, false);
dropper.addEventListener('drop', uploadFile, false);
document.getElementById('file_upload').addEventListener('change', uploadFile, false);
function uploadFile(e)
{
e.preventDefault();
dropper.style.background = '#fff';
dropper.style.borderStyle = 'dashed';
var files = (e.dataTransfer || e.target).files,
filesLen = files.length;
for (var i = 0 ; i < filesLen ; i++)
{
if(files[i] != '')
{
var newDiv = document.createElement("div");
newDiv.setAttribute("class","image_div");
newDiv.innerHTML = '<img id="chargement" src="../includes/chargement.gif"/>';
document.getElementById("upload").appendChild(newDiv);
doAJAX(newDiv,files[i]);
}
}
}
function doAJAX(div,file)
{
var form = new FormData();
form.append('file', file);
if(window.XMLHttpRequest)
{
xhr=new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open('POST', "./traitement_upload.php", true);
xhr.onload = function (e)
{
if(xhr.readyState==4 && xhr.status==200)
{
div.innerHTML = xhr.responseText;
}
}
xhr.send(form);
}

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

jQuery dnd file upload for multiple targets

I'm using jQuery dnd file upload plugin for a project. All example of dnd uploader use id as a selector. For multiple items they used different dropzone declaration.
How can I change the plugin setting for multiple dropzone where the selector will be a class or something else to grab multiple elements with a single dropzone initiation?
Since this is using jQuery, couldn't you use the standard jQuery multiple selector method? It would look like this:
$("#drop1, #drop2, #drop3").dropzone();
Or if you are trying to do a class, you would do this:
$(".drop_zone").dropzone();
This isn't tested, and I have never used this plugin. I'm just assuming this would work since it is based off jQuery.
Since that isn't working, try replacing the code for jquery.dnd-file-upload.js with the following:
(function ($) {
$.fn.dropzone = function (options) {
var opts = {};
var uploadFiles = function (files) {
$.fn.dropzone.newFilesDropped(); for (var i = 0; i < files.length; i++) {
var file = filesi?;
// create a new xhr object var xhr = new XMLHttpRequest(); var upload = xhr.upload; upload.fileIndex = i; upload.fileObj = file; upload.downloadStartTime = new Date().getTime(); upload.currentStart = upload.downloadStartTime; upload.currentProgress = 0; upload.startData = 0;
// add listeners upload.addEventListener("progress", progress, false);
xhr.onload = function (event) {
load(event, xhr);
};
xhr.open(opts.method, opts.url); xhr.setRequestHeader("Cache-Control", "no-cache"); xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); xhr.setRequestHeader("X-File-Name", file.fileName); xhr.setRequestHeader("X-File-Size", file.fileSize); xhr.setRequestHeader("Content-Type", "multipart/form-data"); xhr.send(file);
$.fn.dropzone.uploadStarted(i, file);
}
};
var drop = function (event) {
var dt = event.dataTransfer; var files = dt.files;
event.preventDefault(); uploadFiles(files);
return false;
};
var log = function (logMsg) {
if (opts.printLogs) {
// console && console.log(logMsg);
}
};
// invoked when the input field has changed and new files have been dropped // or selected var change = function (event) {
event.preventDefault();
// get all files ... var files = this.files;
// ... and upload them uploadFiles(files);
};
var progress = function (event) {
if (event.lengthComputable) {
var percentage = Math.round((event.loaded 100) / event.total); if (this.currentProgress != percentage) {
// log(this.fileIndex + " --> " + percentage + "%");
this.currentProgress = percentage; $.fn.dropzone.fileUploadProgressUpdated(this.fileIndex, this.fileObj, this.currentProgress);
var elapsed = new Date().getTime(); var diffTime = elapsed - this.currentStart; if (diffTime >= opts.uploadRateRefreshTime) {
var diffData = event.loaded - this.startData; var speed = diffData / diffTime; // in KB/sec
$.fn.dropzone.fileUploadSpeedUpdated(this.fileIndex, this.fileObj, speed);
this.startData = event.loaded; this.currentStart = elapsed;
}
}
}
};
var load = function (event, xhr) {
var now = new Date().getTime(); var timeDiff = now - this.downloadStartTime; if (opts.onLoadComplete) {
opts.onLoadComplete(xhr.responseText);
} $.fn.dropzone.uploadFinished(this.fileIndex, this.fileObj, timeDiff); log("finished loading of file " + this.fileIndex);
};
var dragenter = function (event) {
event.stopPropagation(); event.preventDefault(); return false;
};
var dragover = function (event) {
event.stopPropagation(); event.preventDefault(); return false;
};
// Extend our default options with those provided. opts = $.extend({}, $.fn.dropzone.defaults, options);
var id = this.attr("id"); var dropzone = document.getElementById(id);
log("adding dnd-file-upload functionalities to element with id: " + id);
// hack for safari on windows: due to not supported drop/dragenter/dragover events we have to create a invisible <input type="file" /> tag instead if ($.client.browser == "Safari" && $.client.os == "Windows") {
var fileInput = $("<input>"); fileInput.attr({
type: "file"
}); fileInput.bind("change", change); fileInput.css({
'opacity': '0', 'width': '100%', 'height': '100%'
}); fileInput.attr("multiple", "multiple"); fileInput.click(function () {
return false;
}); this.append(fileInput);
} else {
dropzone.addEventListener("drop", drop, true); var jQueryDropzone = $("#" + id); jQueryDropzone.bind("dragenter", dragenter); jQueryDropzone.bind("dragover", dragover);
}
return this;
};
$.fn.dropzone.defaults = {
url: "", method: "POST", numConcurrentUploads: 3, printLogs: false, // update upload speed every second uploadRateRefreshTime: 1000
};
// invoked when new files are dropped $.fn.dropzone.newFilesDropped = function () { };
// invoked when the upload for given file has been started $.fn.dropzone.uploadStarted = function (fileIndex, file) { };
// invoked when the upload for given file has been finished $.fn.dropzone.uploadFinished = function (fileIndex, file, time) { };
// invoked when the progress for given file has changed $.fn.dropzone.fileUploadProgressUpdated = function (fileIndex, file,
newProgress) {
};
// invoked when the upload speed of given file has changed $.fn.dropzone.fileUploadSpeedUpdated = function (fileIndex, file,
KBperSecond) {
};
})(jQuery);
This was suggested by the user rik.leigh#gmail.com here http://code.google.com/p/dnd-file-upload/wiki/howto

File data from input element

In Firefox 3 it is possible to access the contents of a <input type="file"> element as in the following.
Assume a form with the following element:
<input type="file" id="myinput">
Now the data of the file selected can be accessed with:
// Get the file's data as a data: URL
document.getElementById('myinput').files[0].getAsDataURL()
Is there a cross-browser way to accomplish the same thing?
Firefox documentation for this feature:
https://developer.mozilla.org/en/nsIDOMFileList
https://developer.mozilla.org/en/nsIDOMFile
This is possible in at least Chrome, Firefox and Safari: Reading Files.
see associated jsfiddle
function readBlob(opt_startByte, opt_stopByte) {
var files = document.getElementById('files').files;
if (!files.length) {
alert('Please select a file!');
return;
}
var file = files[0];
var start = parseInt(opt_startByte) || 0;
var stop = parseInt(opt_stopByte) || file.size - 1;
var reader = new FileReader();
// If we use onloadend, we need to check the readyState.
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
document.getElementById('byte_content').textContent = _.reduce(evt.target.result,
function(sum, byte) {
return sum + ' 0x' + String(byte).charCodeAt(0).toString(16);
}, '');
document.getElementById('byte_range').textContent =
['Read bytes: ', start + 1, ' - ', stop + 1,
' of ', file.size, ' byte file'].join('');
}
};
var blob;
if (file.slice) {
blob = file.slice(start, stop + 1);
}else if (file.webkitSlice) {
blob = file.webkitSlice(start, stop + 1);
} else if (file.mozSlice) {
blob = file.mozSlice(start, stop + 1);
}
console.log('reader: ', reader);
reader.readAsBinaryString(blob);
}
document.querySelector('.readBytesButtons').addEventListener('click', function(evt) {
if (evt.target.tagName.toLowerCase() == 'button') {
var startByte = evt.target.getAttribute('data-startbyte');
var endByte = evt.target.getAttribute('data-endbyte');
readBlob(startByte, endByte);
}
}, false);

Categories