Download all images on website using JavaScript

Tram Ho

  1. The Problem Certainly in practice when doing projects, the download feature is a lot. For example, simply uploading 01 image we can do like this. As the code below is too simple, right inside the <a> tag we can expect the “download” attribute to be downloaded when the user clicks the link.

    At first glance, it is clear that uploading images is simple, right. So what if we arise the need to click once and download all the images? That feature is not a difficult feature, especially for those of you who are too “adept” in javascript, but for some “newbie” you also have to spend some time searching for solutions. So let me help you. This article will not be about algorithms or technology, but simply share my ways to help you handle these features faster. Those who are too “experienced” can skip this post
  2. Solution Where we will start to click event at the button to download the image


    After we have an array of image paths we will process the filename we will use the splitUrl row. If you want all the images rendered in the same name, skip this step and will fix the hardware name in the next step.

    Now that the image’s name is available, I will process the image. Normally, when you get the image path from the server to return, your computer will not be able to save it to your computer, forcing you to process it in the correct format. The Javascript provided for you to handle that, I use arrayBuffer to save the image as typedArray , initialize it into an object when going through Blob and finally create a path from that ojbect createObjectURL. We will have a form as shown in the image

    At this point, it’s too easy and the image name and image link are also available, I just need to initialize the <a> setAttribute tag and download append to the body and trigger click and the tag a just created to download the image. I will show the code below for your reference:


    Note: If the image returned from the server is a link from cdn, then that cdn must access CORS, when you can download the image.
  3. Conclusion So I have helped “newbies” handle a task very easily using javascript. The article is based on personal knowledge, so the shortcomings are unavoidable, if people have any questions or feedback, please comment below so that I can answer and supplement the article to be more complete. Thank you for watching the article.
Share the news now

Source : Viblo