1. 程式人生 > >TP5-上傳圖片方法

TP5-上傳圖片方法

/*
 * 檢查base64編碼的圖片格式
 */

function check_base64_img_string($img) {
    if (!isset($img)) {
        $msg = array(
            'code' => false,
            'message' => '引數錯誤'
        );
        return $msg;
    }

    $img = base64_decode($img);
    $img_size = getimagesizefromstring($img);
    if
($img_size == false) { $msg = array( 'code' => false, 'message' => '非圖片檔案' ); return $msg; } $img_size[2] = intval($img_size[2]); if ($img_size[2] < 1 || $img_size[2] > 3) {//1 = GIF,2 = JPG,3 = PNG $msg = array( 'code'
=> false, 'message' => '圖片格式錯誤' ); return $msg; } $ext = ''; switch ($img_size[2]) { case 1: $ext = '.gif'; break; case 2: $ext = '.jpg'; break; case 3: $ext = '.png'
; break; } return array('code' => true, 'ext' => $ext); } //將 base64 後的圖片內容儲存為檔案 function save_base64_img_file($img_string = '', $type = '') { $type_array = array( 'business_license', //營業執照 'identity_card', //身份證 'bocc', //中銀附件 'driving_license', //行駛證 'opening_accounts', //開戶許可 'authorization', //授權委託書 'price_single', //核價單 'attached', //掛靠協議 'policy', //保險單 'invoice', //發票 ); if (!$img_string || !in_array($type, $type_array)) { return array( 'code' => false, 'message' => '檔案分類不存在' ); } $request = check_base64_img_string($img_string); if (!$request['code']) {//沒通過檢查 return $request; } $upload_path = str_replace('\\', '/', ROOT_PATH); $path = 'public/uploads/' . $type . '/' . date('Ymd') . '/'; $upload_path = $upload_path . $path; if (!is_dir($upload_path)) { mkdir($upload_path, 0755, true); } $file_name = get_rand_str(15, 1) . $request['ext']; $file_path = $upload_path . '/' . $file_name; $state = file_put_contents($file_path, base64_decode($img_string)); if ($state === false) { return array( 'code' => false, 'message' => '圖片儲存失敗' ); } return array( 'code' => true, 'path' => '/' . $path . $file_name, ); }