Found this article which showing how to distinguish file upload from directory How to handle dropped folders but they not explain how I can handle the directory upload. Having difficulties to find any example. Anyone know how to get File instance of each file in directory?
Copied from that article:
<div id=”dropzone”></div>
var dropzone = document.getElementById('dropzone');
dropzone.ondrop = function(e) {
var length = e.dataTransfer.items.length;
for (var i = 0; i < length; i++) {
var entry = e.dataTransfer.items[i].webkitGetAsEntry();
if (entry.isFile) {
... // do whatever you want
} else if (entry.isDirectory) {
... // do whatever you want
}
}
};
Use DirectoryReader directoryEntry.createReader() , readEntries() for folders or , FileEntry file() for single or multiple file drops.
html
<div id="dropzone"
ondragenter="event.stopPropagation(); event.preventDefault();"
ondragover="event.stopPropagation(); event.preventDefault();"
ondrop="event.stopPropagation(); event.preventDefault(); handleDrop(event);">
Drop files
</div>
javascript
function handleFiles(file) {
console.log(file);
// do stuff with `File` having `type` including `image`
if (/image/.test(file.type)) {
var img = new Image;
img.onload = function() {
var figure = document.createElement("figure");
var figcaption = document.createElement("figcaption");
figcaption.innerHTML = file.name;
figure.appendChild(figcaption);
figure.appendChild(this);
document.body.appendChild(figure);
URL.revokeObjectURL(url);
}
var url = URL.createObjectURL(file);
img.src = url;
} else {
console.log(file.type)
}
}
function handleDrop(event) {
var dt = event.dataTransfer;
var files = dt.files;
var length = event.dataTransfer.items.length;
for (var i = 0; i < length; i++) {
var entry = dt.items[i].webkitGetAsEntry();
if (entry.isFile) {
// do whatever you want
console.log("isFile", entry.isFile);
entry.file(handleFiles);
} else if (entry.isDirectory) {
// do whatever you want
console.log("isDirectory", entry.isDirectory);
var reader = entry.createReader();
reader.readEntries(function(entries) {
entries.forEach(function(dir, key) {
dir.file(handleFiles);
})
})
}
}
}
plnkr http://plnkr.co/edit/eGAnbA?p=preview
After you drag some file from your disk. This event.dataTransfer.file is your fileList object.
Your could create a formData then
Add files from fileList to formData one by one.
In the end you could submit formData to server with Ajax
Related
I want to download all audio files from folder but this code only download last file in folder.
var element = document.getElementById("songs");
var audionum = element.getElementsByTagName('audio').length;
var zipcounter = 0;
var zip = new JSZip();
var zipName = 'Test.zip';
for(var i = 0; i < audionum; i++){
var audiosrc = document.getElementsByTagName('source')[i].getAttribute("src");
var audiosrcsplit = audiosrc.split('/')[1];
// loading a file and add it in a zip file
JSZipUtils.getBinaryContent(audiosrc, function (err, data) {
if(err) {
throw err; // or handle the error
}
zip.file(audiosrcsplit, data, {binary:true});
zipcounter++;
if (zipcounter == audionum) {
zip.generateAsync({type:'blob'}).then(function(content) {
saveAs(content, zipName);
});
}
});
}
For ES6 , you can try replacing var with let (block scope).
If you are making use of ES5 then, try something like below.
var element = document.getElementById("songs");
var audionum = element.getElementsByTagName('audio').length;
var zipcounter = 0;
var zip = new JSZip();
var zipName = 'Test.zip';
function addToZip(audiosrc, audiosrcsplit) {
JSZipUtils.getBinaryContent(audiosrc, function (err, data) {
if (err) {
throw err; // or handle the error
}
zip.file(audiosrcsplit, data, {
binary: true
});
zipcounter++;
if (zipcounter == audionum) {
zip.generateAsync({
type: 'blob'
}).then(function (content) {
saveAs(content, zipName);
});
}
});
}
for (var i = 0; i < audionum; i++) {
var audiosrc = document.getElementsByTagName('source')[i].getAttribute("src");
var audiosrcsplit = audiosrc.split('/')[1]; // loading a file and add it in a zip file
addToZip(audiosrc, audiosrcsplit);
}
I want to add all files to a blob and zip then upload using plupload.
I've googled for days looking for answer and have not been able to figure it out.
uploader.bind('FilesAdded', function(up, files) {
plupload.each(files,function(file) {
source = file.getSource();
relative_path = source.relativePath
var fileCount = up.files.length;
var ids = $.map(up.files, function (item) { return item.id; });
alert(source);
arrayFiles[index] = source;
if (index + 1 == files_remaining){
output = pako.gzip(arrayFiles , {to : "Uint8Array"});
myBlob = new Blob(arrayFiles);
uploader.addFile(myBlob);
index = 0;
}
index++;
I want to open outlook with an attachement (zip) using Javascript.
It's working fine if the file in in some directory in the computer client.
this.sendEmail = function (zip) {
try {
var theApp = new ActiveXObject("Outlook.Application");
var objNS = theApp.GetNameSpace('MAPI');
var theMailItem = theApp.CreateItem(0); // value 0 = MailItem
theMailItem.to = ('test#gmail.com');
theMailItem.Subject = ('test');
theMailItem.Body = ('test');
theMailItem.Attachments.Add(zip);
theMailItem.display();
}
catch (err) {
alert(err.message);
}
};
But What I want to do is to add the file that I have alredy in memory
this.SenddZip = function (docDescription, fileName) {
var zip = new JSZip();
for (var i = 0; i < docDescription.length; i++) {
var doc = docDescription[i];
zip.file(doc.core_documenttitle + doc.core_fileextension, doc.fileBase64, { base64: true });
}
Utils.sendEmail(zip);
// Generate the zip file asynchronously
zip.generateAsync({ type: "blob" })
.then(function (content) {
// Force down of the Zip file
var name = "documents";
if (fileName) {
name = fileName;
}
// location.href = "data:application/zip;base64," + content;
saveAs(content, name + ".zip");
Utils.sendEmail(xxxxxxxx);
});
};
If their is no solution for this :
Is their a way to download the document without the confirmation dialog ?
saveAs ask always for confirmation before to store the file.
Thank you
I am trying to upload multiple images. So I read that I can generate a temporary url and send them with ajax.
The idea is push the url created with filereader into an array and the send with ajax but the url's are not pushed properly. When I see the result I got like an empty array:
But if I click the arrow I can see the url's inside
But them seems Inaccessible.
This is my code:
$('form').on('submit',function(e) {
e.preventDefault();
var filesToUpload = document.getElementById("myFile");
var files = filesToUpload.files;
var fd = new FormData();
var arr = [];
if (FileReader && files && files.length) {
for (i=0; i< files.length; i++){
(function(file) {
var name = file.name;
var fr = new FileReader();
fr.onload = function () {
arr.push(fr.result);
}
fr.readAsDataURL(file);
})(files[i]);
}
console.log(arr);
}
});
The final idea is convert to string JSON.stringify(arr) and then parse in php json_decode($_POST['arr']).
Of course this is not working because JSON.stringify(arr) gets empty.
Maybe the following simple solution works for you? I placed your console.log() and your ajax call into the fr.onload() method but fire it only, after your results array has been filled up with all values:
$('form').on('submit',function(e) {
e.preventDefault();
var filesToUpload = document.getElementById("myFile");
var files = filesToUpload.files;
var fd = new FormData();
var arr = [];
if (FileReader && files && files.length) {
for (var i=0; i< files.length; i++){
(function(file) {
var name = file.name;
var fr = new FileReader();
fr.onload = function () {
arr.push(fr.result);
if(arr.length==files.length) {
console.log(arr);
// place your ajax call here!
}
}
fr.readAsDataURL(file);
})(files[i]);
}
}
});
So I'm doing a simple multiple image upload script using javascript, but socket.io has to be used in order to get the image into the database. In order to run previews I have been taking event.target.result and putting it as the image src on a div. Is there any way I can store the this in an array for each image so that I can transfer it over the socket, and have it load on the other side? When I try to load it into an array, it's always undefined.
for (var i = 0; file = files[i]; i++) {
name[i] = files[i].name;
// if the file is not an image, continue
if (!file.type.match('image.*')) {
continue;
}
reader = new FileReader();
reader.onload = (function (tFile) {
return function (evt) {
var div = document.createElement('div');
var miniDiv = document.createElement('div');
div.id = "photoDiv";
div.innerHTML = '<img style="width: 120px; height: auto;" src="' + evt.target.result + '" />';
div.className = "photos";
var data = evt.target.result;
picture[i] = data;
document.getElementById('filesInfo').appendChild(div);
document.getElementById('previewDiv').appendChild(document.getElementById('filesInfo'));
};
}(file));
reader.readAsDataURL(file);
}
uploadFiles();
}
Don't make functions within a loop like that, it can lead to unexpected things.
I would suggest using JSHint, it's very helpful.
You made two mistakes:
1) You should pass i variable to your closure together with file.
2) The most important: reader.onload is a function that will be called not immediately, but in some delay, and as a result it will be called after uploadFiles() call. That's why you get an empty picture.
Try to rewrite your code as follows:
var done = 0;
var picture = [];
for (var i = 0; file = files[i]; i++) {
name[i] = files[i].name;
// if the file is not an image, continue
if (!file.type.match('image.*')) {
if (++done === files.length) {
uploadFiles();
}
continue;
}
reader = new FileReader();
reader.onload = (function (tFile, index) {
return function (evt) {
//[...]
picture[index] = data;
//[...]
if (++done === files.length) {
//the last image has been loaded
uploadFiles();
}
};
}(file, i));
reader.readAsDataURL(file);
}