php 接收jQuery通過Ajax上傳圖片

1.upload.html

<html>	
	<head>
		<meta charset="utf-8">
		<script src="jquery.min.js"></script>
	</head>
	<style>
		/*.thumb-image{*/
			/*width:200px;*/
			/*height:200px;*/
		/*}*/
	</style>
	<body>

	<!--<img src="timer.jpg" height="91" width="121" id="file"/>-->
	<input type="file" id="fileUpload" multiple>
	<div id="image-holder">

	</div>
	<button id="upload">上傳</button>
	<script>
		$(function () {
		    $("#fileUpload").on('change', function () {
				var countFiles = $(this)[0].files.length;
                console.log(countFiles);
                var imgPath =  $(this)[0].value;
                console.log(imgPath);
                var ext = imgPath.substring(imgPath.lastIndexOf('.')+1).toLowerCase();
                console.log(ext);
                var image_holder = $('#image-holder');
				image_holder.empty();
				if(ext == 'jpg' || ext == 'png' || ext =='jpeg' || ext == 'gif'){
                    for (var i = 0; i < countFiles; i++) {
                        console.log(111);
                        var reader = new FileReader();
                        reader.readAsDataURL($(this)[0].files[i])
						reader.onload = function (ev) {
                            console.log(ev);
                            $('<img>',{
							    'src':ev.target.result,
								'class':'thumb-image'
							}).appendTo(image_holder)
                        };
						image_holder.show();
                    }
				}
            });

			$('#upload').on('click', function () {
                var form = new FormData();
                var file = $('.thumb-image').eq(0).attr('src');
                form.append('file',file);
                $.ajax({
                    url: './upload.php',
                    type:'post',
                    data:form,
                    processData: false,
                    contentType: false,
                    dataType: 'json',
                    success:function (res) {
                        console.log(res);
                    }
                })
            })
        })
	</script>

2.upload.php

$str = $_POST['file'];
$image = explode(',', $str);
$filename = date('YmdHis').'.png';
$res = file_put_contents($filename, base64_decode($image[1]));
var_dump($filename);

注意:PHP通過file_put_contents方法寫入文件時,先通過64解碼,不然圖片無法顯示

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章