php後臺接受上傳圖片

配合上個博文的,搗鼓了一個php後臺的東西,雖然不怎麼懂,但慢慢來,仍是能夠的。傳送門php

java太很差學了,玩玩php,知足一下本身。html

那個圖片壓縮的效果很明顯,竟然壓縮了好幾倍。java

<?php
header('Content-type:text/html; charset="utf-8"');
$base64_image_content=$_POST["file"];
//var_dump($$base64_image_content);
if(preg_match('/^(data:\s*image\/(\w+);base64,)/i',$base64_image_content,$result)){
    $type=$result[2];
    $new_file="upload/".date("Ymd",time())."/";
    if(!file_exists($new_file)){
        /*權限問題,0777是最好的,其餘可能會被禁止*/
        mkdir($new_file,0777);
        echo "建立成功";
    }else{
        echo "建立失敗";
    }
    $new_file=$new_file.time().".{$type}";
    if(file_put_contents($new_file,base64_decode(str_replace($result[1],"",$base64_image_content)))){
        echo "成功";
    }else{
        echo "失敗";
    }
    
}else{
    echo "不匹配!!";
}
?>

表單提交,傳送圖片json

<?php
header('Content-type:text/html; charset="utf-8"');
$upload_dir = 'uploads/';

if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
    exit_status(array('code'=>1,'msg'=>'錯誤提交方式'));
}

if(array_key_exists('file',$_FILES) && $_FILES['file']['error'] == 0 ){
    
    $pic = $_FILES['file'];
    
    if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
        exit_status(array('code'=>0,'msg'=>'上傳成功','url'=>$upload_dir.$pic['name']));
    }
    
}
echo $_FILES['file']['error'];
exit_status(array('code'=>1,'msg'=>'出現了一些錯誤'));

function exit_status($str){
    echo json_encode($str);
    exit;
}
?>
相關文章
相關標籤/搜索