หมวดหมู่: jQuery

พรีวิวรูปที่อัพโหลดพรีวิวรูปที่อัพโหลด

ถ้าเวลาเรา upload รูปขึ้น server คงจะดีถ้าเราเห็นว่าเราเลือกภาพถูกรึเปล่า หรือขนาดมันใหญ่เกินไปมั๋ย เราทำได้โดยการแสดงภาพ Preview ขนาด ความกว้าง ความสูง และทำการตรวจสอบก่อนจะได้ไม่เสียเวลา

ตัวอย่าง jQuery Upload Image Preview Demo

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery Upload Image Preview</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
	<label>เฉพาะรูปภาพ
		<input type="file" name="pic" accept="image/*">
	</label>
</form>
<img id="picPreview">
<dl>
	<dt>image dimensions width</dt>
	<dd id="picDimensionsWidth"></dd>
	<dt>image dimensions height</dt>
	<dd id="picDimensionsHeight"></dd>
	<dt>lastModified</dt>
	<dd id="picLastModified"></dd>
	<dt>lastModifiedDate</dt>
	<dd id="picLastModifiedDate"></dd>
	<dt>name</dt>
	<dd id="picName"></dd>
	<dt>original file upload path</dt>
	<dd id="picPath"></dd>
	<dt>size</dt>
	<dd id="picSize"></dd>
	<dt>type</dt>
	<dd id="picType"></dd>
</dl>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
$ ('[name="pic"]') .change (function () {

	/* original file upload path */
	$ ('#picPath') .text ($ (this) .val ()) ;

	var file = this.files[0];
	/* get picture details */
	$ ('#picLastModified') .text (file.lastModified) ;
	$ ('#picLastModifiedDate') .text (file.lastModifiedDate) ;
	$ ('#picName') .text (file.name) ;
	$ ('#picSize') .text (file.size) ;
	$ ('#picType') .text (file.type) ;

	/* set image preview */
	if (! file.type.match (/image.*/)) {
		return true;
	}
	var reader = new FileReader () ;
	reader.onload = function (event) {
		$ ('#picPreview') .attr ('src', event.target.result) ;

		/* get image dimensions */
		var image = new Image () ;
		image.src = reader.result;
		image.onload = function () {
			$ ('#picDimensionsWidth') .text (image.width) ;
			$ ('#picDimensionsHeight') .text (image.height) ;
		};

	}
	reader.readAsDataURL (file) ;

}) ;
</script>
</body>
</html>