1. 程式人生 > >PHP上傳圖片

PHP上傳圖片

str func height adas post ont utf-8 mkdir dataurl

HTML部分:
<
div class="sc-img"></div> <p><input type="file" class="file" id="img"></p>
javascript部份:
$(‘#img‘).change(function(){ var img = event.target.files[0]; // 判斷是否圖片 if(!img){ return ; } // 判斷圖片格式 if
(!(img.type.indexOf(‘image‘)==0 && img.type && /\.(?:jpeg|jpg|png|gif)$/.test(img.name)) ){ alert(‘圖片只能是jpeg,jpg,gif,png‘); return ; } var reader = new FileReader(); reader.readAsDataURL(img); reader.onload = function(e){ $.ajax({ url:
"scImg.php", method: ‘POST‘, data: { img:e.target.result}, success: function(msg) { // alert(‘上傳成功‘); $(‘.sc-img‘).html(‘<img style=‘+‘height:100%;‘+‘ src="‘ + msg.img + ‘">‘); console.log(
‘src‘,msg.img); },error:function(){ console.log(‘上傳失敗‘); } }); } });
php部分:scImg.php
<?php $path="uppic/"; if(!file_exists($path)) { mkdir("$path", 0777); } $img = isset($_POST[‘img‘])? $_POST[‘img‘] : ‘‘; // 獲取圖片 list($type, $data) = explode(‘,‘, $img); // 判斷類型 if(strstr($type,‘image/jpeg‘)!=‘‘){ $ext = ‘.jpeg‘; }elseif(strstr($type,‘image/gif‘)!=‘‘){ $ext = ‘.gif‘; }elseif(strstr($type,‘image/png‘)!=‘‘){ $ext = ‘.png‘; }elseif(strstr($type,‘image/jpg‘)!=‘‘){ $ext = ‘.jpg‘; } // 生成的文件名 $photo = time().$ext; // 生成文件 file_put_contents($path."/".$photo, base64_decode($data), true); // 返回 header(‘content-type:application/json;charset=utf-8‘); $ret = array(‘img‘=>$path.$photo); echo json_encode($ret); ?>

PHP上傳圖片