圖片base64上傳時可能遇到的問題


base64上傳圖片時服務器接到的值可能會丟失字符串

解決方法如下:(分為單個上傳和多個上傳)

<?php
$BASE_DIR = "../";
//文件上傳
$img = isset($_POST['img'])?$_POST['img']:'';
$dir = isset($_POST['dir'])?$_POST['dir']:'img';
$result = array();
$arr = [];
if (is_array($img)){
    foreach ($img as $v){
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $v, $result)) {
            $type = $result[2];
            $file = "images/{$dir}/" . date('Ymd', time()) . "/";
            if (!file_exists($file)) {
                //檢查是否有該文件夾,如果沒有就創建,並給予最高權限
                mkdir($file, 0777, true);
            }
            $file = $file . time(). '_' .rand(0,100) . ".{$type}";
            $data = str_replace(' ','+',$v);
            if (file_put_contents($file, base64_decode(str_replace($result[1], '', $data)))) {
                $arr[] = $file;
            } else {
                return false;
            }
        }
    }
    echo json_encode($arr);
} else {
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img, $result)){
        $type = $result[2];
        $file = "images/{$dir}/" . date('Ymd', time()) . "/";

        if (!file_exists($file)) {
            //檢查是否有該文件夾,如果沒有就創建,並給予最高權限
            mkdir($file, 0777, true);
        }
        $file = $file . time() . '_' . rand(0, 100) . ".{$type}";
        $data = str_replace(' ', '+', $img);
        if (file_put_contents($file, base64_decode(str_replace($result[1], '', $data)))) {
            $file = substr($file,strpos($file,'/')+1);
            echo json_encode($file);
        } else {
            return false;
        }
    }
}

主要就是把服務器接到的值做一個字符串替換,解決問題!

 

以上就是這次的全部內容!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM