How to add to an existing FileList object with JavaScript? - javascript

I am creating a drag and drop file upload zone. When I upload multiple files at a time it works but I need it to be able to support uploading in multiple stages. I know that the issue below is that I am setting files each time, but I can't figure out the right way to get more files added to dFiles each time the method is called
var dFiles;
//var dFiles = []
var holder = document.getElementById('holder');
holder.ondrop = function (e) {
e.preventDefault();
dFiles = (e.dataTransfer.files);
//dFiles.push(e.dataTransfer.files);
}
I tried initilaizing dfiles as an empty array and adding the files (commented out above). Later this created a data type mismatch error when I was reading the file data
for (var i = 0; i < dFiles.length; i++) {
reader = new FileReader();
reader.readAsDataUrl(dFiles[i]); //error
}

e.dataTransfer.files is a list of files.
You will have to add each file separately to dFiles:
var files = e.dataTransfer.files;
for (var i = 0, l = files.length; i < l; i++) {
dFiles.push(files[i]);
}
Or the ES6 way:
dFiles.push(...e.dataTransfer.files);

Related

jQuery move local files to another directory

I would like to create a function which will count the files from a directory.
If there are 5 files, move the oldest file to another directory.
I found a code sample, but it is not working for my case.
var myFileList = Folder("C:/Test").getFiles();
var folderCount = GetFoldersCount(myFileList) ;
$.writeln(folderCount);
function GetFoldersCount(fileList) {
var folderCount = 0;
console.log(folderCount);
for (var i = 0; i < fileList.length; i++) {
var myFile = myFileList[i];
if (myFile instanceof Folder)
folderCount++;
}
return folderCount
}
I am getting the error "Folder" is not defined.
Its impossible directly access local files by JS for seccurity issue.
Another thing is that you can access files on drive over Ajax call and process
on response. Using Ajax you can send request what you want to do it on background.
You used example at InDesign forum. I dont know InDesign but I am not sure that it will work.
Otherwise look for documentation about HTML5 File API. Hope that you will find answer.
https://w3c.github.io/FileAPI/
some examples:
https://www.html5rocks.com/en/tutorials/file/dndfiles/
I found out the solution for this task, which works perfect for me.
I call the function with the initial directory:
moveErrorFiles('C:\\Folder1');
And below are the 2 simple functions I use.
function moveErrorFiles(fileDir) {
var fileSysObj, file, folder, fileCounter, currentFile;
var fileMumber = 0;
fileSysObj = new ActiveXObject("Scripting.FileSystemObject");
folder = fileSysObj.GetFolder(fileDir);
fileCounter = new Enumerator(folder.files);
for (; !fileCounter.atEnd(); fileCounter.moveNext()) {
currentFile = fileCounter.item();
fileMumber++;
if (fileMumber > 5) {
moveFile(currentFile);
}
}
} //function moveErrorFiles() ends here
function moveFile(fileToMove) {
var object = new ActiveXObject("Scripting.FileSystemObject");
var file = object.GetFile(fileToMove);
file.Move("C:\\Folder2\\");
console.log("File was moved successfully");
} //function moveFile() ends here

Loop multiple files from input, save each file readAsDataURL data to array

I need your help with following problem:
I have HTML input which supports multiple files;
I upload let's say 5 files;
Each file is processed: it is readAsDataURL by FileReader and data of file is saved to object(there will be other params saved too, that is why object), which is pushed to array.
After I run flow I described, length of final array is NOT changed.
I believe problem is in async behaviour, but I cannot understand how should I change code to make it work, that is why I ask you for a help. Please find code below:
var controls = document.getElementById('controls');
function processUploadedFilesData(files) {
if (!files[0]) {
return;
};
var uploads = [];
for (var i = 0, length = files.length; i < length; i++) {
(function(file) {
var reader = new FileReader();
//I need object, as other params will be saved too in future;
var newFile = {};
reader.readAsDataURL(file);
reader.onloadend = function(e) {
newFile.data = e.target.result;
uploads.push(newFile);
}
})(files[i]);
}
return uploads;
}
controls.addEventListener('change', function(e) {
var uploadedFilesOfUser = processUploadedFilesData(e.target.files);
alert(uploadedFilesOfUser.length);
});
Codepen example - https://codepen.io/yodeco/pen/xWevRy

I want to load images withen the folder and want to get all images in base64 in my js for future use

i am facing the issue i always get the last image in my image array due to kind of Filereader library function onloadend.
how can i get base64 for all images in my folder.
<input id="file-input" multiple webkitdirectory type="file" />
var input = document.getElementById('file-input');
var file_names = "";
var entries_length = 0;
var entries_count = 0;
var image = new Array();
var obj = {};
var j = 0;
input.onchange = function(e) {
var files = e.target.files; // FileList
entries_length = files.length;
console.log(files);
for (var i = 0, f; f = files[i]; ++i){
console.log("i:"+i);
entries_count = entries_count + 1;
//console.debug(files[i].webkitRelativePath);
if(files[i].type=="image/jpeg")
{
var string = files[i].webkitRelativePath;
var name = string.split("/")[3]; //this is because my image in 3rd dir in the folder
var reader = new FileReader();
reader.onloadend = function() {
obj.name = string.split("/")[3];
obj.image = reader.result;
image[j] = obj;
j = j+1;
}
reader.readAsDataURL(files[i]);
}
}
console.log(image);
}
The issue is caused by the asynchronous loading of files. You iterate over the array and set the onloadend handler for the reader each time, then start loading by calling readAsDataURL.
One problem is that by the time your first image loads, it is possible the for loop has completed, and i is already at the last index of the array.
At this point, obtaining the path from files[i].webkitRelativePath will give you the last filename, and not the one you are expecting.
Check the example for readAsDataURL on MDN to see one possible solution - each load is performed in a separate function, which preserves its scope, along with file.name. Do not be put off by the construction they are using: [].forEach.call(files, readAndPreview). This is a way to map over the files, which are a FileList and not a regular array (so the list does not have a forEach method of its own).
So, it should be sufficient to wrap the loading logic in a function which takes the file object as a parameter:
var images = [];
function loadFile(f) {
var reader = new FileReader();
reader.onloadend = function () {
images.push({
name : f.name, // use whatever naming magic you prefer here
image : reader.result
});
};
reader.readAsDataURL(f);
}
for (var i=0; i<files.length; i++) {
loadFile(files[i]);
}
Each call of the function 'remembers' the file object it was called with, and prevents the filename from getting messed up. If you are interested, read up on closures.
This also has the nice effect of isolating your reader objects, because I have a sneaking suspicion that, although you create a new 'local' reader each iteration, javascript scoping rules are weird and readers could also be interfering with each other (what happens if one reader is loading, but in the same scope you create a new reader with the same variable name? Not sure).
Now, you do not know how long it would take for all images to be loaded, so if you want to take an action right after that, you would have to perform a check each time an onloadend gets called. This is the essence of asynchronous behavior.
As an aside, I should note that it is pointless to manually keep track of the last index of images, which is j. You should just use images.push({ name: "bla", image: "base64..." }). Keeping indices manually opens up possibilities for bugs.

how can I get path of file from input api

hy users
I try to get the path of a file via html5 js
I try:
jQuery("#pfad").change(function(evt){
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
for (var i = 0; i < files.length; i++) {
alert(files[i].path);
}
but path isn't a attribute of this file object....
what can i do?
You can't get the full file path due to security limitations. However you can read the name of the file:
jQuery("#pfad").change(function (evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
for (var i = 0; i < files.length; i++) {
console.log(files[i].name);
}
});
Most browsers dont allow to get the full file path on client side. But in case of Google Chrome and Mozilla Firefox you can get the path by:
jQuery("#pfad").change(function(evt){
var path = $(this).val();
alert(path);
}
I tested it on both of these browsers.

How to run code on last iteration of html5 read file method?

In this javascript/jquery code I attempt to read multiple files and store them in a dictionary.
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
var f, filename;
for (var i = 0; i<files.length; i++) {
f = files[i];
filename = escape(f.name);
if (filename.toLowerCase().endsWith(".csv")) {
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(e) {
var text = reader.result;
var arrays = $.csv.toArrays(text);
frequencies[filename] = arrays;
generateMenuFromData();
});
// Read in the image file as a data URL.
reader.readAsText(f);
}
}
}
I read only the .csv files. I want to run generateMenuFromData(); only on the last time the reader.onload function runs.
I can't find a good way to do this properly. Does anyone know how?
Thanks.
Increase a counter inside the event handler. If it is the same the length of the array, execute the function. A more structured approach would be to use promises, but in this simple case it would suffice:
function handleFileSelect(evt) {
var files = evt.target.files;
var f, filename, loaded = 0;
for (var i = 0; i<files.length; i++) {
f = files[i];
filename = escape(f.name);
if (filename.toLowerCase().endsWith(".csv")) {
var reader = new FileReader();
reader.onload = (function(filename, reader) {
return function(e) {
frequencies[filename] = $.csv.toArrays(reader.result);
loaded += 1; // increase counter
if (loaded === files.length) {
// execute function once all files are loaded
generateMenuFromData();
}
};
}(filename, reader)); // <-- new scope, "capture" variable values
reader.readAsText(f);
}
}
}
Now, your real problem might be that you are creating a closure inside the loop. That means when the load event handlers are called, filename and reader will refer to the values the variable had in the last iteration of the loop. All handlers share the same variables.
See also Javascript closure inside loops - simple practical example.

Categories

Resources