Last active
August 28, 2018 18:04
-
-
Save jgmuchiri/c4063d749824f968e06149c1dc734f87 to your computer and use it in GitHub Desktop.
Download images in a page - VueJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<div> | |
<div class="row"> | |
<div class="col-sm-9"> | |
<button class="btn btn-success" v-on:click="dlImages()"> | |
<i class="fa fa-download"></i> | |
Download photos | |
</button> | |
<hr/> | |
<div class="row"> | |
<div class="col-xs-12 col-sm-4 col-md-3 col-lg-3" v-for="pic in pics"> | |
<img :title="pic.title" :src="pic.url" class="rig-img" style="width:200px;"/> | |
<h4>{{pic.title}}</h4> | |
</div> | |
</div> | |
</div> | |
</div> | |
</div> | |
</template> | |
<script> | |
export default { | |
created() { | |
}, | |
data() { | |
return { | |
title: 'Rig pics', | |
pics: this.rigPics(this.$route.params.id) | |
} | |
}, | |
computed: { | |
totalPhotos() { | |
return this.rig.photos.length; | |
} | |
}, | |
methods: { | |
rigPics: function (id) { | |
let pic = []; | |
.... | |
return pic; | |
}, | |
dlImages: function () { | |
//convert the image from the remove url to base64 | |
function imgToBase64(url, callback) { | |
let xhr = new XMLHttpRequest(); | |
xhr.onload = function () { | |
let reader = new FileReader(); | |
reader.onloadend = function () { | |
callback(reader.result); | |
} | |
reader.readAsDataURL(xhr.response); | |
}; | |
xhr.open('GET', url); | |
xhr.responseType = 'blob'; | |
xhr.send(); | |
} | |
let images = document.getElementsByClassName('rig-img'); | |
let i = 0; | |
setInterval(function () { | |
if (images.length > i) { | |
let img = images[i].src; //get image url | |
let ext = img.split('.').pop(); //get file extension | |
ext = ext.split('?')[0]; //remove any trailing stuff after extension (e.g. img.jpg?type=media) | |
let name = images[i].title + '.' + ext; //file name with extension | |
imgToBase64(img, function (imageData) { | |
let link = document.createElement("a"); | |
link.setAttribute('href', 'data:application/octet-stream'); | |
link.download = name; | |
link.href = imageData; | |
link.click(); | |
}); | |
i++; | |
} | |
}, 1000); //adjust interval based on how fast you want them downloaded. Default is 1 sec to avoid DOM overload. | |
} | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment