1. 程式人生 > >php實現base64圖片上傳方式例項程式碼 前端介面問題

php實現base64圖片上傳方式例項程式碼 前端介面問題

php實現base64圖片上傳方式例項程式碼 html程式碼

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>簡單的html5 File測試 for pic2base64</title> 
<style> 
</style> 
<script> 
  window.onload = function(){ 
    var input = document.getElementById("demo_input"); 
    var result= document.getElementById("result"); 
    var img_area = document.getElementById("img_area"); 
    if ( typeof(FileReader) === 'undefined' ){
      result.innerHTML = "抱歉,你的瀏覽器不支援 FileReader,請使用現代瀏覽器操作!"; 
      input.setAttribute('disabled','disabled'); 
    }else{
      input.addEventListener('change',readFile,false);
    } 
  }
  function readFile(){
    var file = this.files[0]; 
    //這裡我們判斷下型別如果不是圖片就返回 去掉就可以上傳任意檔案  
    if(!/image\/\w+/.test(file.type)){
      alert("請確保檔案為影象型別"); 
      return false; 
    }
    var reader = new FileReader(); 
    reader.readAsDataURL(file); 
    console.log();
    reader.onload = function(e){ 
        result.innerHTML = this.result; 
        img_area.innerHTML = '<div class="sitetip">圖片img標籤展示:</div>![]('+this.result+')'; 
    }
  } 
</script> 
</head>
 
<body> 
  <form action="file.php" method="post">
  <input type="file" value="sdgsdg" id="demo_input" /> 
  <textarea name="img" id="result" rows=30 cols=300></textarea> 
  <p id="img_area"></p> 
  <input type="submit" value="提交">
</form>
</body> 
</html>

PHP功能塊程式碼

<?php
/**
 * base64圖片上傳
 * @param $base64_img
 * @return array
 */
$base64_img = trim($_POST['img']);
$up_dir = './upload/';//存放在當前目錄的upload資料夾下
 
if(!file_exists($up_dir)){
  mkdir($up_dir,0777);
}
 
if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)){
  $type = $result[2];
  if(in_array($type,array('pjpeg','jpeg','jpg','gif','bmp','png'))){
    $new_file = $up_dir.date('YmdHis_').'.'.$type;
    if(file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))){
      $img_path = str_replace('../../..', '', $new_file);
      echo '圖片上傳成功</br>![](' .$img_path. ')';
    }else{
          echo '圖片上傳失敗</br>';
 
    }
  }else{
    //檔案型別錯誤
  echo '圖片上傳型別錯誤';
  }
 
}else{
  //檔案錯誤
  echo '檔案錯誤';
}