How to unzip and download all images from zip folder using javascript? - javascript

I have tried using jszip and able to extract only 10 images from the zip file.But ZIp file contains 450 images.
By using the below code I am able to download 10 images only. Not extracting all images of zip folder.
function unzipfeb146() {
var i = 0;
// fetch('file:///C:/CBTOffline/Images/8687.Zip')
fetch('http://localIP/CBT/R3Images/QBQuestionImages/8688.zip')
.then(response => response.arrayBuffer())
.then(data => {
// Extract the files from the zip
const zip = new JSZip();
return zip.loadAsync(data);
})
.then(zip => {
// Download each file
Object.keys(zip.files).forEach(filename => {
debugger;
zip.files[filename].async('blob').then(blob => {
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
`your text`
link.download = filename;
document.body.appendChild(link);
link.click();
var img = document.createElement("img");
img.src = URL.createObjectURL(blob);
img.id = i + 1;
document.body.appendChild(img);
i = i + 1;
//const image = new Image();
//image.src = URL.createObjectURL(blob);
//image.id = fileName;
//document.body.appendChild(image);
//document.body.removeChild(link);
});
});
})
.catch(error => console.error(error));
}
Expected out put as below :

To create a download link for a zipped file, you can use the tag with the href attribute pointing to the location of the zipped file, like this:
Download file

Related

Download PDF in browser with blob

I can not quite wrap my head around on how to download a PDF from a google spreadsheet PDF Export Weblink. I generated a testing spreadsheet for this case.
I understand that I need to implement encodeURIComponent and/or "Buffer.from" to the blob but however I do it, it only downloads a broken PDF for me.
This is what I currently have in its rawest form. Thank you for your support!
Node JS:
const fetch = require('node-fetch');
var url = "https://docs.google.com/spreadsheets/d/1fLjKASR_g5wsvOjjJi6RclqMVd2o_1On-OfimXtId4E/export?exportFormat=pdf&format=pdf&size=A4&fzr=true&gid=477517973&sheetnames=false&printtitle=false&pagenumbers=false&gridlines=false&portrait=true&fitw=true&fith=true&top_margin=0.20&bottom_margin=0.20&left_margin=0.20&right_margin=0.20";
let blob = await fetch(url).then(r => r.blob());
// then send blob variable to javascript
Javascript:
function downloadURI(name) {
var uri = 'data:application/pdf;base64,' + blob;
var link = document.createElement('a');
link.download = name;
link.href = uri;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
delete link;
}
downloadURI("test"+".pdf")
I thought that from var uri = 'data:application/pdf;base64,' + blob; in your script, in this case, it is required to convert the downloaded data as the base64. Although I'm not sure about the relationship between the scripts between Node JS: and Javascript:, in your situation, how about the following modification?
From:
let blob = await fetch(url).then(r => r.blob());
To:
let buf = await fetch(url).then((r) => r.arrayBuffer());
const data = Buffer.from(buf).toString("base64");
By this, you can use data as follows.
var uri = 'data:application/pdf;base64,' + data;
Note:
As the additional information, for example, if you want to download your Spreadsheet as a PDF file using only Javascript, you can also use the following script. But, in this case, the Spreadsheet is required to be publicly shared. Please be careful about this.
async function downloadURI(name) {
var url = "https://docs.google.com/spreadsheets/d/1fLjKASR_g5wsvOjjJi6RclqMVd2o_1On-OfimXtId4E/export?exportFormat=pdf&format=pdf&size=A4&fzr=true&gid=477517973&sheetnames=false&printtitle=false&pagenumbers=false&gridlines=false&portrait=true&fitw=true&fith=true&top_margin=0.20&bottom_margin=0.20&left_margin=0.20&right_margin=0.20";
let blob = await fetch(url).then((r) => r.blob());
var f = new FileReader();
f.readAsDataURL(blob);
f.onload = d => {
var uri = d.target.result;
var link = document.createElement('a');
link.download = name;
link.href = uri;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
delete link;
}
}
downloadURI("test"+".pdf")

JS download doesn't download entire file

I am trying to download a csv file with 3607 lines (1.0 Mb):
const hiddenElement = document.createElement('a');
const fileContent = `data:text/csv;charset=ansi,${res.data}`;
hiddenElement.href = fileContent;
hiddenElement.target = '_blank';
hiddenElement.download = 'file.csv';
hiddenElement.click();
The content at res.data is complete (as well as fileContent), but when i download the csv, the file only has 149 lines (4.4 Kb) instead of the original size.
Can someone help me please?
The problem was that URLs cant have more than 2,048 characters
I faced the same problem and the same CSV download used to work earlier and download complete file.
had to change to the following:
const blob = new Blob([csvData], { type: 'text/csv' })
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a')
link.setAttribute('href', url)

CSV file from server URL not downloading

I'm messing with a piece of code to download a CSV from server. this is what I'm trying:
downloadCSVTemp(){
let name = 'report.csv';
const response = api.getReportCSV()
.then((res)=>{
const blob = new Blob([res], { type: "data:text/csv;charset=utf-8," });
const blobURL = window.URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.download = name;
anchor.href = blobURL;
anchor.dataset.downloadurl = ["text/csv", anchor.download, anchor.href].join(
":"
);
anchor.click();
});
}
getReportCSV(){
return axios.get("/export/assessments/");
}
I intend to download a csv file from server url by an axios call, But this code is downloading an csv file which can't be opend by the browser & full of garbage data. What's the problem here ?
The res argument contains Axios response object. When creating the blob, you should use res.data:
new Blob([res.data], { type: "data:text/csv;charset=utf-8," });

I want to record audio input using javascript and save it to disk

Hi I am a beginner so I am not having much knowledge about javascript so kindly help me in solving my issue.
I am facing problem in saving audio input. The audio which is saved onto the disk is somehow corrupted and not proper (.mp3/.wav) file.
Here is my javascript code
function saveBlob(blob, fileName) {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
}
function startRecording(){
var device = navigator.mediaDevices.getUserMedia({audio:true});
var items = [];
device.then( stream => {
var recorder = new MediaRecorder(stream);
recorder.ondataavailable = e => {
items.push(e.data);
if(recorder.state == "inactive")
{
var blob = new Blob(items, {type: 'audio/wav'});
alert(blob.type);
saveBlob(blob, 'myRecording.wav');
}
}
recorder.start();
setTimeout(()=>{
recorder.stop();
}, 4000);
});
I think the problem is that you save the file with the wrong mimeType. As far as I know there is no browser which can record WAV files out of the box.
A quick fix would be to change the part which creates the file.
var blob = new Blob(items, {type: recorder.mimeType});
alert(blob.type);
saveBlob(blob, `myRecording.wav${blob.type.split('/')[1].split(';')[0]}`);
Or you could use a package like extendable-media-recorder which allows to record WAV files directly.

Download a file from URL with different file name

I have below functionality using JavaScript
The back end gives me a URL to download a file from like below -
https://something.org/FILENAME.ZIP
So I file name is fixed as FILENAME.ZIP
But while downloading a file , the file should get downloaded with custom file name like CUSTOMFILENAME.ZIP instead of FILENAME.ZIP
So,
1)The file should get downloaded from URL : https://something.org/FILENAME.ZIP
2)But it should get saved with different file name as :
CUSTOMFILENAME.ZIP
3)I have tried below programme from url - how to download a file from url using javascript or jquery?
var a = document.createElement("a");
a.href = url;
var fileName = CUSTOMFILENAME;
a.download = fileName;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
a.remove();
But still file gets downloaded with whatever file name mentioned in URL
Can anybody please help me here ?
The file should get saved with CUSTOMFILENAME I provide and not fileName specified as part of URL
Try this see if it works,
const documentName = "CustomFileName"; // here your file name
fetch("http://yourdomain.com")
.then(res => {
return res.blob();
})
.then(blob => {
const href = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.download = documentName;
a.href = href;
a.click();
a.href = "";
})
.catch(err => console.error(err));
you are giving a object as download name give a string

Categories