JQuery 圖片壓縮base64 php上傳

html部分

 <form id="upload_form" enctype ="multipart/form-data">
         <input type="file" style="display: none" id="upload_head">
 </form>

jquery部分

$(document).on('click','#head',function(){
            $('#upload_head').trigger('click');
        });


        $("#upload_head").change(function(){
            var file = this.files[0];
            if (window.FileReader) {
                var reader = new FileReader();
                // 圖片文件轉換爲base64
                reader.readAsDataURL(file);
                reader.onload = function(){
                    let img = this.result;
                    $.ajax({
                        url : "#",
                        type : "POST",
                        data : {
                            img_base64:img,
                        },    
                        dataType:"json",
                        success : function(data) {
                            if(data.status==1){
                                $("#head").attr("src",img);
                            }else{
                                $.toptip(data.info,'danger');
                            }

                        }
                    });


                }
            }
        });

php部分

if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base, $result)){
            $type = $result[2];
            $new_file = "public/avatar_uploads/".date('Ymd',time())."/";
            if(!file_exists($new_file))
            {
                mkdir($new_file, 0700);
            }
            $str=rand(1000,9999);
            $new_files = $new_file.date('Ymdhis',time()).$str.".{$type}";

            if (file_put_contents($new_files, base64_decode(str_replace($result[1], '', $base)))){

                //刪除原路徑圖片
                $prvImg=‘’;
                if(!empty($prvImg)){
                    $prvImg='.'.$prvImg;
                    @unlink($prvImg);
                }
                $path="/".$new_files;
           		
           		//存入數據庫
              
            }
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章