Native JavaScript realizes unified package and download of photos and custom name for the linked array of photos

In the past two days, we have encountered a problem that the front end can get a json object. The requirement is to extract the specific links in the json and throw them into an array, and then write a function to put them into a file one by one and package them into a zip file for download. Many methods have been found before, but because js relies on the browser and other reasons, it can only be handled in a single file. Finally, the rogue asked some elder martial sisters. She was very good and immediately found demo (see the end of the film). After some transformation, it was finally solved. Well, not much to say about the code: it includes multiple processing and unified processing packaged into ZIP processing and provides custom naming + suffix processing.

HTML:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
	<head>
		<meta charset="utf-8" />
		<title>Details page</title>
		<script src="./js/jquery.min.js"></script>
		<link rel="stylesheet" type="text/css" href="./css/detail.css">
		<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
		<script src="https://cdn.bootcss.com/bootstrap-table/1.15.4/bootstrap-table.js"></script>
		<script src="https://cuikangjie.github.io/JsonExportExcel/dist/JsonExportExcel.min.js"></script>
		<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
		<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.5/jszip.min.js"></script>
		<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>
	</head>
	<body>
	<div class="download">
		<button onclick="downloadExcel()">exportExcel</button><span id="downloadExcel"></span>
		<button onclick="downloadPhoto()">exportPhoto</button><span id="downloadPhoto"></span>
	</body>
	<script type="text/javascript" src="./js/detail2.js"></script>
</html>

JavaScript:


var globalUrl = "http://00.000.000.00:8089/admin"
var datas = [];
function downloadExcel() {
	// alert("download!")
	var names = [];
	var jsonData = [];
	var suffix = [];
	$(function() {
		$.ajax({
			type: "get",
			url: globalUrl + "/getAll",
			success: function(data) {
				datas=data;
				var strs="";
					// console.log("888")
					alert("Being generated......!")
				$("table").append(strs);
				for(let i=0;i<data.length;i++) {
					var obj = {
						id: data[i].id,
						cementPlant: data[i].cementPlant,//Cement plant
						affiliatedCompanyDistributor: data[i].affiliatedCompanyDistributor,//Company / distributor
						licensePlateNumber: data[i].licensePlateNumber,//License plate number
						vehicleOwner: data[i].vehicleOwner,//Driver
						cellPhoneNumber: data[i].cementPlant,//Phone number
						idNumber: data[i].idNumber,//ID card No.
						vehicleType: data[i].vehicleType,//Vehicle type
						loads: data[i].loads,//load
						axleNumber: data[i].axleNumber,//Axle number
						installationTime: data[i].installationTime,//Installation time
					};
					names.push(data[i].photoFileUrl.slice(37, 46));//.replace("/","-")
					var tmp=data[i].photoFileUrl.substring(data[i].photoFileUrl.length-3);
					suffix.push("."+tmp);
					jsonData.push(obj);//http://60.205.218.96:8083/uploadFile/2020/2/12
				}
				// alert(JSON.stringify(jsonData));
				// //Column headings, separated by commas, each comma is separated by a cell
				var str = "id number,Cement plant,Affiliated company/Distributor,License plate number,Driver,Phone number,ID card No.,Vehicle type,load,Axle number,Installation time\n";
				//Add \ tto prevent tables from displaying scientific notation or other formats
				for(let i = 0 ; i < jsonData.length ; i++ ){
					for(let item in jsonData[i]){
						str+=`${jsonData[i][item] + '\t'},`;
					}
					str+='\n';
				}
				//Encodeuriccomponent solves Chinese code disorder
				let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
				//By creating a tag
				var link = document.createElement("a");
				link.href = uri;
				//Name the downloaded file
				link.download =  "jsonExcel.xls";
				document.body.appendChild(link);
				link.click();

			},
			error: function(data) {
				alert("Data download failed!")
			}

		});
	})
}

	function downloadPhoto(){
	// photoFileUrl
		var names = [];
		var jsonData = [];
		var suffixs = [];
		var photoLink = [];
		$.ajax({
			type: "get",
			url: globalUrl + "/getAll",
			success: function(data) {
				var strs="";
				var arrays = [];
				// console.log("888")
				// alert("generating! ""
				// alert(JSON.stringify(data));
				$("table").append(strs);
				for(let i=0;i<data.length;i++) {
					var obj = {
						id: data[i].id,
						cementPlant: data[i].cementPlant,//Cement plant
						affiliatedCompanyDistributor: data[i].affiliatedCompanyDistributor,//Company / distributor
						licensePlateNumber: data[i].licensePlateNumber,//License plate number
						vehicleOwner: data[i].vehicleOwner,//Driver
						cellPhoneNumber: data[i].cementPlant,//Phone number
						idNumber: data[i].idNumber,//ID card No.
						vehicleType: data[i].vehicleType,//Vehicle type
						loads: data[i].loads,//load
						axleNumber: data[i].axleNumber,//Axle number
						installationTime: data[i].installationTime,//Installation time
					};
					names.push(data[i].id+"_"+data[i].photoFileUrl.slice(37, 46));//.replace("/","-")
					var tmp=data[i].photoFileUrl.substring(data[i].photoFileUrl.length-3);
					suffixs.push("."+tmp);
					jsonData.push(obj);//http://60.205.218.96:8083/uploadFile/2020/2/12
					photoLink.push(data[i].photoFileUrl);
				}
				// alert(JSON.stringify(jsonData));
				// alert(names);
				// alert(suffixs);
				// alert(photoLink);

				//js downloads files and supports modifying file names
				//url: file address filename: the name you want to modify to "http://60.205.218.96:8083/uploadFile/2020/2/13/52d0882643ef40139c50716af16478c8.jpg"
				var url=data[1].photoFileUrl;
				var filename=names[1]+suffixs[1];
				function download(url, filename) {
					getBlob(url, function (blob) {
						saveAs(blob, filename);
					});
				};
				function getBlob(url, cb) {
					var xhr = new XMLHttpRequest();
					xhr.open('GET', url, true);
					xhr.responseType = 'blob';
					xhr.onload = function () {
						if (xhr.status === 200) {
							cb(xhr.response);
						}
					};
					xhr.send();
				}
				function saveAs(blob, filename) {
					if (window.navigator.msSaveOrOpenBlob) {
						navigator.msSaveBlob(blob, filename);
					} else {
						var link = document.createElement('a');
						var body = document.querySelector('body');
						link.href = window.URL.createObjectURL(blob);
						link.download = filename;
						// fix Firefox
						link.style.display = 'none';
						body.appendChild(link);
						link.click();
						body.removeChild(link);
						window.URL.revokeObjectURL(link.href);
					};
				}
				// download(url,filename);

				//Leaflet
				// photoLink.map(function(i){
				// 	var a = document.createElement('a');
				// 	a.setAttribute('download','');
				// 	a.href=i;
				// 	document.body.appendChild(a);
				// 	a.click();
				// })

				function packageImages(){
					$('#downloadPhoto').text('processing...';
					var imgs = photoLink;//$('img');
					// alert(JSON.stringify(imgs));
					var imgsSrc = [];
					var imgBase64 = [];
					var imageSuffix = [];//Picture suffix
					var zip = new JSZip();
					zip.file("readme.txt", "Photo taken'ID_date'name\n");
					var img = zip.folder("images");

					for(var i=0;i<photoLink.length;i++){
						var src = imgs[i];//getAttribute("src");
						var suffix = src.substring(src.lastIndexOf("."));
						imageSuffix.push(suffix);

						getBase64(imgs[i])//.getAttribute("src")
							.then(function(base64){
								console.log(base64)
								imgBase64.push(base64.substring(22));
							},function(err){
								console.log(err);//Print exception information
							});
					}
					alert("3");
					function tt(){
						setTimeout(function(){
							if(imgs.length == imgBase64.length){
								for(var i=0;i<imgs.length;i++){
									img.file(names[i]+imageSuffix[i], imgBase64[i], {base64: true});//Just put it into base64
									console.log(imgBase64[i]);
								}
								zip.generateAsync({type:"blob"}).then(function(content) {
									saveAs(content, "photos.zip");
								});
								$('#status').text('processing complete..... ).
							}else{
								$('#status').text('completed: '+ imgBase64.length+'/'+imgs.length);
								tt();
							}
						},100);
					}
					tt();
				}
				//Incoming picture path, returning base64
				function getBase64(img){
					function getBase64Image(img,width,height) {
						var canvas = document.createElement("canvas");
						canvas.width = width ? width : img.width;
						canvas.height = height ? height : img.height;
						var ctx = canvas.getContext("2d");
						ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
						var dataURL = canvas.toDataURL();
						return dataURL;
					}
					var image = new Image();
					image.crossOrigin = 'Anonymous';
					image.src = img;
					var deferred=$.Deferred();
					if(img){
						image.onload =function (){
							deferred.resolve(getBase64Image(image));
						}
						return deferred.promise();
					}
				}
				packageImages();
			},
			error: function(data) {
				alert("Data download failed!")
			}
		});
	}


$(function() {
	$.ajax({
		type: "get",
		url: globalUrl + "/getAll",
		success: function(data) {
			//	console.log(res)
			var str = ""
			for (var i = 0; i < data.length; i++) {
				str += '<tr><td>' + data[i].id + '</td><td>' + data[i].cementPlant + '</td><td>' + data[i].affiliatedCompanyDistributor +
					'</td><td>' +
					data[i].licensePlateNumber + '</td><td>' + data[i].vehicleOwner + '</td><td>' + data[i].cellPhoneNumber +
					'</td><td>' + data[i].idNumber + '</td><td>' +
					data[i].vehicleType + '</td><td>' + data[i].loads + '</td><td>' + data[i].axleNumber + '</td><td>' + data[
						i].installationTime
					// + '</td><td> <button id="delUser" name=' +
					// data[i].id + ' onclick="delUser(' + data[i].id +
					// '"> delete < / button > < button class =" BTN BTN primary update "data toggle =" modal "'+
					// 'data target = "ාmovemodal" > Modify < / button > < button class = "viewbtn" > View < / button > < td > < tr >'

			}//alert(str);
			$("table").append(str);
		}
	});
})

//delete
function delUser(uid) {
	var mymessage = confirm("Are you sure to delete?");
	console.log(uid);
	if (mymessage == true) {
		$.ajax({
			url: globalUrl + "/del",
			async: false,
			type: 'get',
			data: {
				id: uid
			},
			success: function(data) {
				window.location.href = window.location.href;
				alert("Delete successful");
				if (data == 0) {
					$("button[name=refresh]").click();
				}
			},
			error: function(data) {
				alert("Server busy")
			}
		});

	}
}


var that = null
//External Modify button event
$(document).on("click", ".update", function() {
	that = $(this).parents("tr")
	var arr = []
	$(this).parents("tr").find("td").each(function() {
		arr.push($(this).text())
	})
	$("#movemodal").find("input").each(function(i) {
		$(this).val(arr[i])
	})
})

//Modify button event in modal box (detailed modify page)
$(".addbtn_ok").click(function() {
	var id = $("#id").val();
	var cementPlant = $("#cementPlant").val();
	var affiliatedCompanyDistributor = $("#affiliatedCompanyDistributor").val();
	var licensePlateNumber = $("#licensePlateNumber").val();
	var vehicleOwner = $("vehicleOwner").val();
	var cellPhoneNumber = $("#cellPhoneNumber").val();
	var idNumber = $("#idNumber").val();
	var vehicleType = $("#vehicleType").val();
	var loads = $("#loads").val();
	var axleNumber = $("#axleNumber").val();
	var installationTime = $("#installationTime").val();

	$.ajax({
		url: globalUrl + "/updateInfo",
		type: "post",
		data: {
			id: id,
			cementPlant: cementPlant,
			affiliatedCompanyDistributor: affiliatedCompanyDistributor,
			licensePlateNumber: licensePlateNumber,
			vehicleOwner: vehicleOwner,
			cellPhoneNumber: cellPhoneNumber,
			idNumber: idNumber,
			vehicleType: vehicleType,
			loads: loads,
			axleNumber: axleNumber,
			installationTime: installationTime
		},
		dataType: "text",
		contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
		success: function(data) {
			if (data == "success") {
				alert("Data update failed,Please try again.!");
			} else {
				alert("\n\n Data updated successfully,Please check!");
				window.location.href = window.location.href;
			}
		}
	});
})

//Cancel modification button event in modal box (detailed modification page)
$(document).on("click", ".addbtn_no", function() {
	$(".movefade").fadeOut(600)
})

$(document).on("click", ".modal-header i", function() {
	$(".movefade").fadeOut(600)
})

//External view button event
var arrView = []
$(document).on("click", ".viewbtn", function() {
	arrView = []
	$(".viewfade").fadeIn(600)
	$(this).parent().siblings().each(function() {
		arrView.push($(this).text())
	})
	$(".modal-body").find("p span").each(function(i) {
		$(this).text(arrView[i])
		console.log(arrView)
	})
})

//View cancel button event in modal box
$(document).on("click", ".addbtn_no", function() {
	$(".viewfade").fadeOut(600)
})

$(document).on("click", ".modal-header i", function() {
	$(".viewfade").fadeOut(600)
})

From elder martial sister:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<style>
			img{
				width: 200px;
				height: 150px;
			}
		</style>
	</head>
	<body>

		<!-- Note that the path of the picture and the domain name of the project must not be cross domain
		//For example: the project is deployed in the domain name www.baidu.com/index.html
		//Then the image path should be changed to www.baidu.com/img/2.png -- >
		<!-- Links can come from the network other URL -->
		<img src="http://60.205.218.96:8089/uploadFile/2020-2-19/331.jpg" />
		<img src="http://60.205.218.96:8089/uploadFile/2020-2-19/337.jpg" />
		
		<br /><br />
		<button onclick="packageImages()">packageImages</button><span id="status"></span><br /><br />
		
		<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
		<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.5/jszip.min.js"></script>
		<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>
		<script type="text/javascript">
		function packageImages(){
			$('#status').text("processing..... "";
			
			var imgs = $('img');
			alert(JSON.stringify(imgs));
			var imgsSrc = [];
			var imgBase64 = [];
			var imageSuffix = [];//Picture suffix
			var zip = new JSZip();
		    zip.file("readme.txt", "Case details\n");
		    var img = zip.folder("images");
		    
			for(var i=0;i<imgs.length;i++){
				var src = imgs[i].getAttribute("src");
				var suffix = src.substring(src.lastIndexOf("."));
				imageSuffix.push(suffix);
				
				 getBase64(imgs[i].getAttribute("src"))
		            .then(function(base64){
		            	console.log(base64)
		            	imgBase64.push(base64.substring(22));
		            	 
		            },function(err){
		                  console.log(err);//Print exception information
		            }); 
		           
			}
			function tt(){
				setTimeout(function(){
					if(imgs.length == imgBase64.length){
						for(var i=0;i<imgs.length;i++){
							img.file(i+imageSuffix[i], imgBase64[i], {base64: true});//Just put it into base64
							console.log(imgBase64[i]);
						}
						zip.generateAsync({type:"blob"}).then(function(content) {
					        saveAs(content, "images.zip");
					    });
					    $('#status').text('processing complete..... ).
					    
					}else{
						$('#status').text('completed: '+ imgBase64.length+'/'+imgs.length);
						tt();
					}
				},100);
				
			}
			tt();
			
		}
 
    //Incoming picture path, returning base64
    function getBase64(img){
        function getBase64Image(img,width,height) {
          var canvas = document.createElement("canvas");
          canvas.width = width ? width : img.width;
          canvas.height = height ? height : img.height;
 
          var ctx = canvas.getContext("2d");
          ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
          var dataURL = canvas.toDataURL();
          return dataURL;
        }
        var image = new Image();
        image.crossOrigin = 'Anonymous';
        image.src = img;
        var deferred=$.Deferred();
        if(img){
          image.onload =function (){
            deferred.resolve(getBase64Image(image));
          }
          return deferred.promise();
        }
      }
    
</script>
	</body>
</html>

/*-------------------Anti climbing statement o--------------------

Author: Yang Mu fa
Copyright notice:
This article is the original article of the blogger. Please attach the link of the source article for the whole reprint!

If you think this article has something to gain for you, please comment and comment on it

Reasonable and high-quality forwarding will also encourage and support me to continue to create,

For more highlights, Baidu can search for yangmufa or:

Personal website: www.yangmufa.com    ,

Open source China: https://my.oschina.net/yangmufa    ,

Gitee: https://gitee.com/yangmufa    ,

GitHub: https://github.com/yangmufa    .

Insist on creation and be good at summarizing high-quality progress of open source sharing.

-------------------Anti climbing statement o--------------------*/

Keywords: Front-end Javascript JSON JQuery github

Added by Braimaster on Wed, 19 Feb 2020 16:03:29 +0200