Get a collection of images packed into a single zip file

My current function downloads multiple images and saves them to a user's "download" folder, although it only works in Chrome.

I am looking to enhance this function by combining the downloaded images into a single zip file.

Below is my existing code. I aim to integrate this with the JSZip API that I came across online at this link.

I have already installed the JSZip API using bower and included the script in my HTML.

The code below successfully downloads multiple individual images:

$scope.downloadPhotos = function() {
    var photoUrls = [];
    for (var x = 0; x < $scope.$parent.photos.length; x++) {

        var p = $scope.$parent.photos[x];
        if (p.isChecked) {
            photoUrls.push($scope.bucketUrl() + p.photoUrl);

        }
    }

    saveImage(photoUrls);
};



/*----this function  saveImage works great (only Chrome)-----*/
function saveImage(urls) {
    var link = document.createElement('a');

    link.setAttribute('download', null);
    link.style.display = 'none';


    document.body.appendChild(link);

    for (var i = 0; i < urls.length; i++) {
        link.setAttribute('href', urls[i]);
        link.click();
    }

    document.body.removeChild(link);
}

Here is an example of the JSZip API code to create a zip file with content:

function create_zip() {
    var zip = new JSZip();
    zip.add("hello1.txt", "Hello First World\n");
    zip.add("hello2.txt", "Hello Second World\n");
    content = zip.generate();
    location.href = "data:application/zip;base64," + content;
}

Now, I’m inquiring about how to merge these two functionalities to place my images into a zipfile. Thank you for your assistance!

Answer №1

If you're looking to zip an array of image URLs, I've created a solution for that.

Check out this link for the code snippet

To customize the structure of the zip folder, you can adjust the following line in the code:

filename = filename.replace(/[\/\*\|\:\<\>\?\"\\]/gi, '').replace("httpsi.imgur.com","");

Answer №2

If you want to download multiple files in Zip format, one option is to utilize jsZip and FileSaver.js. Alternatively, if you are working with Web API and Angularjs, you can create an API method on the server to generate a zip archive file. Then, in Angularjs, you can make a $http post or get api call to download the file as a zip file (Remember to use filesaver to save it in zip format). Here's an example:

Example of an API call in Angularjs:

function downloadFiles(files) {
            return $http.post(baseUrl + 'api/download/files', files, { responseType: 'arraybuffer' });
        }

To download the files, call the above function and use the fileSaver.js method saveAs to save the file in zip format. For instance:

//files - array input of files like http://www.example.com/file1.png', 'http://www.example.com/file2.jpeg', 'http://www.example.com/file3.jpg'];

    downloadFiles(files).then(function (response) {
        //on success
        var file = new Blob([response.data], { type: 'application/zip' });
        saveAs(file, 'example.zip');
    }, function (error) {
        //on error
        //write your code to handle error
    });

Answer №3

Check out this example. Right now, the browser simply triggers the download of a file. If you want to generate a zip file on the client side, your JavaScript code must use ajax calls to access the file content (note: there may be CORS issues if the files are not on the same server).

Here's a summary of the example:

  • Makes ajax calls using JSZipUtils, or just set responseType = "arraybuffer" for modern browsers
  • Organizes ajax calls into promises (the example uses jQuery promises)
  • Adds the results to a zip object
  • Waits for all promises to finish before initiating the download

Answer №4

function convertImageToZip(imageURL){
        var ZIP = new JSZip();
        var picture = new Image();
        picture.crossOrigin = 'Anonymous';
        picture.src = imageURL;
        picture.onload = function() {
            $rootScope.total++;

            var canvass = document.createElement('CANVAS');
            var context = canvass.getContext('2d');
            var dataSourceURL;
            canvass.height = picture.height;
            canvass.width = picture.width;
            context.drawImage(this, 0, 0);
            context.enabled = false;
            dataSourceURL = canvas.toDataURL("Canvas");
            canvass = null;
            var baseSixtyFourString = dataSourceURL.replace("data:image/png;base64,", "");
            
            ZIP.file("NameOfImage", baseSixtyFourString, {base64: true});

            ZIP.generateAsync({type:"blob"}).then(function(data) {
                saveAs(data, "ZippedFileName.zip");
            });

        }

    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Cart cannot function as a constructor

I'm currently learning express.js and trying to implement a shopping cart/session functionality into my project. Below is the code I have written so far, with a question at the end. Here is my cart.js: // Ensure that the file is required correctly b ...

Encountering an uncaught error event while using Yeoman

Whenever I try to run Yeoman, I encounter the following error: events.js:72 throw er; // Unhandled 'error' event ^ Error: spawn ENOENT at errnoException (child_process.js:1001:11) at Process.ChildProcess._handle.one ...

Developing a MySQL Community Server-backed RESTful Web Service with the power of jQuery AJAX

I am currently in the process of developing a RESTful Web Service using MySQL Community Server alongside jQuery AJAX Unfortunately, my usage of jQuery AJAX is not functioning as expected. When attempting to add, delete, update a product, or retrieve all p ...

Creating dynamic input forms in PHP

New to PHP and seeking guidance! I'm in the process of creating a photography website and encountering an issue with a specific page. Essentially, I need this page to display a form with a varying number of inputs. The goal is to have a dynamic visua ...

Tips for successfully incorporating PHP dynamic parameters separated by commas into a JavaScript onclick function

How can I pass PHP dynamic parameters separated by commas to a JavaScript onclick function? Can someone assist me with the correct solution? The code below is not working as expected. echo "<td><a href='#' onclick='editUser(". $row ...

Solution to trigger CSS :hover to refresh following a transition (such as expanding a menu)

While there are existing discussions on this topic, I am presenting my query for two specific reasons: It introduces a potential alternative solution The demo code could be helpful to individuals looking to emulate a menu Following a CSS transition, the ...

Is there a way to incorporate a variable into a JSON URL?

I'm attempting to incorporate a variable I have defined into the JSON URL: var articleName = "test"; $.getJSON( "https://www.googleapis.com/customsearch/v1?key=API_MY&cx=CX_MY&q='+articleName+'&searchType=image&fileType= ...

Combining the power of Angular with a Vanilla JS web application

Seeking your expertise. Situation We are transitioning from a legacy Vanilla JS webapp to Angular. Our plan is to gradually replace isolated components while adding new functionality as separate Angular apps, all within a timeframe of 6-12 months. Challe ...

Utilizing the $set method to capture a jQuery variable and append it to a Vue array object

Currently, I am retrieving data from an API using jQuery's getJson method to extract the information. After successfully obtaining the data, my aim is to assign it to a Vue array object by making use of app.$set. Although I have managed to extract an ...

Sending POST data to a PHP file without the use of jQuery results in AJAX malfunction

I have been struggling to make an ajax alert layer work with a POST method for the past few days, and I cannot figure out why it is not functioning. I have successfully used the same code structure to send form data through ajax using POST on other admin p ...

Annoying AngularJS Scrolling Problem

I am facing an issue with a Container that loads multiple views <md-content flex id="content"> <div ng-view></div> </md-content> One of the loaded views has the following structure: <div layout="column" id="selection-whit ...

When attempting to use the search bar to filter in ReactJs, an error occurs: TypeError - Unable to access properties of undefined (specifically 'filter')

When I receive data from my JSON server on the console, everything looks good. But when I try to type something in order to filter it, an unhandled error occurs with the message: 1 of 1 Unhandled Error Unhandled Runtime Error: TypeError: Cannot read prop ...

I am attempting to adjust the color of the active tab, but I seem to be encountering issues in my code. Can anyone help me

The currently active tab should change along with the text inside the box, but it's not working as expected. I'm struggling to find out why. Here is a fiddle to demonstrate my progress so far: var btn1 = document.getElementById("btn1"); va ...

Using JavaScript, transfer a Base64 encoded image to Google Drive

I've been attempting to upload a Base64 encoded image to Google Drive using a Jquery AJAX POST request. The data successfully uploads to Google Drive, but unfortunately, the image does not display in the Google Drive viewer or when downloading the fil ...

Retrieve the variable only once a response has been received from the POST request

Is there a way to update a variable in my component only after receiving a response from a POST request? Here is the code in component.ts: formSubmit() { this.sent = this.submitProvider.sendByPost(this.form); this.formSent = this.submitProvider.f ...

Unable to retrieve data from MySQL Database using Express Route

Struggling to understand how to execute a MySQL database query within the promise in my route file. Currently, I am developing a RESTful API for interacting with a MySQL database using GET methods. The technologies being utilized are Express for the backen ...

The $state.go function is malfunctioning when called from a different controller

Below is the code snippet: $stateProvider .state('home', { url: "/home", templateUrl: "views/home.tpl.html", controller:"homeController" }) .state('test', { url: '/test', templateUrl: "views/test/dashboard.tpl.html", }); Th ...

Creating arrays in JavaScript with or without the use of jQuery

In my JavaScript script, I am defining this array: var status=[ { "name":"name1", "level":0 }, { "name":"name2", "level":0 }, { "name":"name3", "level":0 }, { "name":" ...

The onload function on the iframe is triggering twice in Internet Explorer 11

I am encountering a strange issue with an iframe in HTML that has an onload function. When using IE11, the onload function is being triggered twice, whereas it works fine in Chrome. Here is the HTML code: <iframe src="someurl" onload="someFunction( ...

Ways to access component load status in Next.js

I'm currently developing a basic Pokedex to showcase all Pokemon. I am utilizing a map function on an array of Pokemon objects to display all the cards in this manner: {pokemons.results.map((el, i) => { return ( <di ...