圖片上傳的兩種實現方式


方式一:采用傳統的multipart/form-data形式

html文件:

 

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>圖片上傳 | 方式一</title>
</head>
<body>
<h2 style="text-align:center">圖片上傳 | 方式一</h2>
<div class="main">
    <form action="upload_file.php" method="post" enctype="multipart/form-data" target="frshowpic" id="myForm">
        <table >
            <tr>
                <td></td>
                <td><input type="file" name="avatar" accept="image/*"></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="上傳圖片"></td>
            </tr>
        </table>
    </form>
    <div id="img">這里顯示預覽圖片</div>

    <!--隱藏iframe-->
    <iframe id="frshowpic" name="frshowpic" style="display:none;"></iframe>
</div>
</body>
<script src="jquery.min.js"></script>
<script type="text/javascript">
    //用來顯示返回結果,隱藏的iframe里面要調用這個顯示圖片的函數
    function showpic(msg, code){
        if (code === 200){
            document.getElementById('myForm').reset();
            document.getElementById('img').innerHTML = '<img src="'+msg+'" width="100">';
        } else{
            alert(msg);
        }
    }
</script>
</html>

 

php文件:

<?php

//配置
$config = array(
    //上傳目錄
    'path' => 'uploads/',
    //限制圖片類型
    'type' => array(
        'gif',
        'jpg',
        'jpeg',
        'pjpeg',
        'png',
        'x-png',
        'bmp'
    ),
    //限制圖片大小(kb)
    'size' => 1024
);

$data = explode(',', $_POST['data']);

if (count($data) == 2) {
    $type = ltrim($data[0], 'data:image/');
    $type = rtrim($type, ';base64');
    if (in_array($type, $config['type'])) {
        $savepath = $config['path'];
        if (!is_dir($savepath)) {
            mkdir($savepath,0777,true);
        }
        $filename = 'org_'.uniqid().mt_rand(1000,9999).'.'.$type;
        $orgin_image_location = $savepath.$filename;
        $base64 = base64_decode($data[1]);
        if (file_put_contents($orgin_image_location, $base64)) {
            exit(json_encode(array('code'=>200, 'msg'=>'上傳成功', 'data'=>'/'.$orgin_image_location)));
        } else {
            exit(json_encode(array('code'=>200, 'msg'=>'上傳失敗')));
        }
    } else {
        exit(json_encode(array('code'=>500, 'msg'=>'圖片類型不正確')));
    }
} else {
    exit(json_encode(array('code'=>500, 'msg'=>'error')));
}

 

方式二:采用base64形式

html文件:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>圖片上傳 | 方式二</title>
</head>
<body>
<h2 style="text-align:center">圖片上傳 | 方式二</h2>
<div class="main">
    <form enctype="multipart/form-data" id="oForm">
        <input type="file" name="file" id="file" onchange="readAsDataURL()" accept="image/*" />
        <input type="button" value="提交" onclick="doUpload()" />
    </form>
    <div>
        <img alt="" id="img"/>
    </div>
</div>
</body>
<script src="jquery.min.js"></script>
<script type="text/javascript">
    //配置
    var config = {
        //限制圖片大小(kb)
        size:1024,
        //限制圖片類型
        type:new Array('jpg', 'jpeg')
    };

    var base64;
    function readAsDataURL() {
        //檢驗是否為圖像文件
        var file = document.getElementById('file').files[0];
        var type = file.type;
        type = type.replace(/image\//, '');
        if (isInArray(config.type, type) !== true) {
            alert('圖片格式錯誤!');

            return false;
        } else {
            if (file.size <= (config.size * 1024)) {
                var reader = new FileReader();
                //將文件以Data URL形式讀入頁面
                reader.readAsDataURL(file);
                reader.onload = function (e) {
                    var result = document.getElementById('img');
                    //顯示文件
                    result.src = this.result;
                    base64 = result.src;
                }
            } else {
                alert('圖片太大!');
            }
        }
    }
    function doUpload() {
        $.ajax({
            url: 'upload_base64.php',
            type: 'POST',
            data: { data: base64 },
            dataType: 'json',
            success: function (res) {
                if (res.code === 200) {
                    console.log(res.data);
                    alert('上傳成功');
                } else {
                    alert(res.msg);
                }
            },
            error: function (res) {
                alert('上傳出錯');
            }
        });
    }

    /**
     * 使用循環的方式判斷一個元素是否存在於一個數組中
     * @param {Object} arr 數組
     * @param {Object} value 元素值
     */
    function isInArray(arr, value){
        for(var i = 0; i < arr.length; i++){
            if(value === arr[i]){
                return true;
            }
        }
        return false;
    }
</script>
</html>

php文件:

<?php

//配置
$config = array(
    //上傳目錄
    'path' => 'uploads/',
    //限制圖片類型
    'type' => array(
        'gif',
        'jpg',
        'jpeg',
        'pjpeg',
        'png',
        'x-png',
        'bmp'
    ),
    //限制圖片大小(kb)
    'size' => 1024
);

$data = explode(',', $_POST['data']);

if (count($data) == 2) {
    $type = ltrim($data[0], 'data:image/');
    $type = rtrim($type, ';base64');
    if (in_array($type, $config['type'])) {
        $savepath = $config['path'];
        if (!is_dir($savepath)) {
            mkdir($savepath,0777,true);
        }
        $filename = 'org_'.uniqid().mt_rand(1000,9999).'.'.$type;
        $orgin_image_location = $savepath.$filename;
        $base64 = base64_decode($data[1]);
        if (file_put_contents($orgin_image_location, $base64)) {
            exit(json_encode(array('code'=>200, 'msg'=>'上傳成功', 'data'=>'/'.$orgin_image_location)));
        } else {
            exit(json_encode(array('code'=>200, 'msg'=>'上傳失敗')));
        }
    } else {
        exit(json_encode(array('code'=>500, 'msg'=>'圖片類型不正確')));
    }
} else {
    exit(json_encode(array('code'=>500, 'msg'=>'error')));
}

 


免責聲明!

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



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