Trying to use jszip to pack png image in zip for user to download (FileSaver.js)
https://stuk.github.io/jszip/
here is my code :
var zip = new JSZip()
var ship_previews = zip.folder('gui/ship_previews')
var ship_previews_ds = zip.folder('gui/ship_previews_ds')
// packing files to zip
let selectedList = $('.mixitup select')
for (let i = 0; i < selectedList.length; i++) {
const imageID = selectedList[i].value
if (imageID.substring(8) != 0) {
let imageFile = $.get('assets/images/ship_previews/' + imageID + '.png')
ship_previews.file(imageID.substring(0, 7) + '.png', imageFile)
let imageFileDS = $.get('assets/images/ship_previews_ds/' + imageID + '.png')
ship_previews_ds.file(imageID.substring(0, 7) + '.png', imageFileDS)
}
}
// download zip
zip.generateAsync({type: 'blob'})
.then(function(content) {
saveAs(content, 'res_mod.zip')
})
And after run it
It downloaded a zip file with folders
But png inside cant read :((
Related
While i am using normal file upload in node js i am getting expected result like below
But my case is different
Image is present inside a folder
Compressed that folder with .zip extension
I am unzipping that zip folder
Want to get the details like fieldname, originalname, encoding, mimetype, buffer and size of each
const subfolderName = sId + '_' + Date.now();
fs.createReadStream(UPLOAD_DIR + zipfilename.originalname)
.pipe(await unzipper.Extract({ path: UPLOAD_DIR + subfolderName }))
.on('entry', entry => entry.autodrain())
.promise()
.then(async () => {
zipfoldername = zipfilename.originalname.replace(/.[^/.]+$/, '');
const arr = zipfoldername.split('-');
zipfoldername = arr[0];
zipfullpath = UPLOAD_DIR + subfolderName + '/' + zipfoldername;
if (zipfullpath) {
let productImagepath = '';
for (const row of productData) {
let imagename = '';
imagename = row.imagename;
let smallImagename = '';
productImagepath = zipfullpath + '/' + imagename;
console.log('productImagepath', productImagepath);
const { buffer, originalname } = productImagepath;
console.log('buffer-', buffer);
console.log('originalname-', originalname);
return;
}
}
});
This is the output I got from the above code
I have set file to be uploaded in s3 bucket,I need to add timestamp before file extension. I m working this code in angular 8 .
this is the method I'm using.
onFileChange(files: FileList) {
for (let fItr in files) {
if (fItr != 'length' && fItr != 'item') {
// var fileExtension = '.' + files[fItr].name.split('.').pop();
// files[fItr].name= Math.random().toString(36).substring(7) + new Date().getTime() + fileExtension;
this.attachment.push(files[fItr]);
this.fileToUpload.push(files.item(parseInt(fItr)));
}
sample input
crawlling.php
fileupload.csv
fileupload.pptx
loading.mp4
sample output (i need the files to be uploaded like this)
crawlling_20180215022222.php
fileupload_20190419062612.csv
fileupload_20200419082612.pptx
loading_20180910081329.mp4
try to append to blob and create new file and push this
onFileChange(files: FileList) {
for (let fItr in files) {
if (fItr != 'length' && fItr != 'item') {
var fileExtension = '.' + files[fItr].name.split('.')[1];
var prefix=files[fItr].name.split('.')[0];
var name= prefix+this.convertDate()+ Math.random().toString(36).substring(7) + new Date().getTime() + fileExtension;
var blob = fItr.slice(0, fItr.size, fItr.type);
var newFile = new File([blob], name, {type: fItr.type});
}
}
}
convertDate(){
var date=new Date();
day=date.getDate();
month=date.getMonth();
month=month+1;
if((String(day)).length==1)
day='0'+day;
if((String(month)).length==1)
month='0'+month;
return date.getFullYear()+""+month+""+ day;
}
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++;
Somwhere around i found code that works fine for drag and drop:
addImage($event) {
// loading the FileList from the dataTransfer
let dataTransfer: DataTransfer = $event.mouseEvent.dataTransfer;
if (dataTransfer && dataTransfer.files) {
// needed to support posting binaries and usual form values
let files: FileList = dataTransfer.files;
// uploading the files one by one asynchrounusly
for (let i = 0; i < files.length; i++) {
let file: File = files[i];
// just for debugging
console.log('Name: ' + file.name + '\n Type: ' + file.type + '\n Size: ' + file.size + '\n Date: ' + file.lastModifiedDate);
// collecting the data to post
let data = new FormData();
data.append('file', file);
data.append('fileName', file.name);
data.append('fileSize', file.size.toString());
data.append('fileType', file.type);
data.append('fileLastMod', file.lastModifiedDate);
// posting the data
let url = 'http://***********.com/gallery/' + this.selectedCategory;
this._http.post(url, data)
.toPromise()
.catch(reason => {
console.log(JSON.stringify(reason));
}).then(result => {
this.getImages();
});
}
}
}
But before i send images out, i want them to preview in modal form.
I was thinking about function that will that take 1 param to works, like:
previewFile(url) {
let elem = document.createElement("img");
elem.className = "previewImage";
elem.src = url
document.getElementById("previewImages").appendChild(elem);
}
But how to get the URL ?
Use this code:
elem.src = URL.createObjectURL(file);
HTML Code
<input type="file" accept="image/*" multiple webkitdirectory mozdirectory msdirectory odirectory directory id="fileURL"/>
Javascript Code:
var files,
file,
extension,
sum,
input = document.getElementById("fileURL"),
output = document.getElementById("fileOutput"),
holder = document.getElementById("fileHolder")
sizeShow = document.getElementById("filesSize");
input.addEventListener("change", function (e) {
files = e.target.files;
output.innerHTML = "";
sum = 0;
for (var i = 0, len = files.length; i < len; i++) {
file = files[i];
extension = file.name.split(".").pop();
if(extension=="jpg"||extension=="png"){
var size = Math.floor(file.size/1024 * 100)/100;
sum = size+sum;
output.innerHTML += "<li class='type-" + extension + "'>"+file.webkitRelativePath + file.name + " (" + size + "KB)</li>";
}else{
file.remove();
}
}
if(sum<1024*1024){
sizeShow.innerHTML = Math.floor(sum/1024*100)/100 + " MB";
}else if(sum>1024*1024){
sizeShow.innerHTML = Math.floor(sum/1024*1024*100)/100 + " GB";
}
}, false);
How do i get just the image in the file upload? accept="image/*" doesn't work for directory.
This does work but the statement file.remove() doesn't work at all.
I guess the input:file is read-only.
How do i solve this?
You can set input.files to a FileList (obtained from e.g. drag and drop), but you cannot create/modify a FileList. So you cannot modify the files of an input to e.g. only contain images.
What you can do, though, is uploading manually (through ajax), and only send files that have a type starting with "image/". See http://jsfiddle.net/WM6Sh/1/.
$("form").on("submit", function(e) {
e.preventDefault();
var files = $(this).find("input").prop("files");
var images = $.grep(files, function(file) {
return file.type.indexOf("image/") === 0; // filter out images
});
var xhr = new XMLHttpRequest();
xhr.open("POST", "/", true);
$(xhr).on("readystatechange", function(e) {
if(xhr.readyState === 4) {
console.log("Done");
}
});
var data = new FormData();
$.each(images, function(i) {
data.append(i, this); // append each image file to the data to be sent
});
console.log(
"Sending %d images instead of all %d files...",
images.length,
files.length
);
xhr.send(data);
});