简易的图床功能

@zgcwkj  2024年11月10日

分类:

网站 代码 

简单实现图床功能的源码分享(原创

PHP实现

简易源码

创建 index.php 文件,作为程序入口
<?php
#phpinfo();
#error_reporting(E_ALL);
#ini_set('display_errors', 1);
date_default_timezone_set('PRC');//时区
header('Content-type:text/html;charset=utf-8');//编码格式
//打开图片
if (isset($_REQUEST['name'])) {
    $key = $_REQUEST['name'];
    header("Location: uploads/$key");
    exit();
} else if (isset($_FILES['file'])) {
    $resultOut = array(
        'state' => false,
        'msg' => '上传失败'
    );
    //上传文件信息
    $fileName = $_FILES['file']['name'];
    $fileSize = $_FILES['file']['size'];
    $tmpName = $_FILES['file']['tmp_name'];
    //检查文件上传大小
    if ($fileSize / 1024 > 1024 * 5) {
        $resultOut['msg'] = '上传文件过太';
        echo json_encode($resultOut);
        exit();
    }
    //上传格式限制
    $fileTypeInfo = [
        'png',
        'jpg',
        'jpeg',
    ];
    $fileType = strtolower(substr(strrchr($fileName, '.'), 1));
    if (!in_array($fileType, $fileTypeInfo)) {
        $resultOut['msg'] = '上传文件格式不正确';
        echo json_encode($resultOut);
        exit();
    }
    //文件名称
    $newFileName = date('YmdHis') . '_' . $fileName;
    //本地存储目录
    if (!file_exists('./uploads')) mkdir('./uploads');
    //移动文件到指定目录
    $filePath = "./uploads/$newFileName";
    if (move_uploaded_file($tmpName, $filePath)) {
        $resultOut['state'] = true;
        $resultOut['msg'] = '上传成功';
        $resultOut['data'] = "uploads/$newFileName";
    }
    echo json_encode($resultOut);
    exit();
}
?>
<!DOCTYPE html>

<html>
<head>
    <meta charset='UTF-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <title>Picture Bed</title>
</head>
<body>
    <div style='margin:30px;'>
        <div style='margin-bottom:10px;'>
            服务端仅能接收:<?php echo ini_get('upload_max_filesize') ?>的文件上传
        </div>
        <div id='fileData'>
            <input type='file' accept='image/*' />
            <input type='submit' value='上传' onclick='upload()' />
        </div>
        <div id='outData' style='margin-top:30px;word-wrap:break-word;'></div>
    </div>
    <script>
        var state = false;
        var file = null;
        //粘贴事件
        document.addEventListener('paste', function(event) {
            var items = event.clipboardData && event.clipboardData.items;
            if (items && items.length) {
                for (var i = 0; i < items.length; i++) {
                    if (items[i].type.indexOf('image') !== -1) {
                        file = items[i].getAsFile();
                        break;
                    }
                }
                //上传文件
                upload();
            }
        });
        //上传事件
        function upload() {
            if(state == true) {
                alert('正在上传文件');
                return;
            }
            let fileDom = document.querySelector('input[type=file]');
            let submitDom = document.querySelector('input[type=submit]');
            let outDom = document.querySelector('#outData');
            //锁定元素
            state = true;
            submitDom.disabled = true;
            //表单提交文件
            const formData = new FormData();
            if (file == null) file = fileDom.files[0];
            formData.append('file', file);
            var request = new XMLHttpRequest();
            request.onreadystatechange = function(event) {
                if (request.readyState == 4 && request.status == 200) {
                    var resultText = request.responseText;
                    var result = JSON.parse(resultText);
                    var outMsg = '';
                    if (result.state == true) {
                        outMsg = result.data;
                    } else {
                        outMsg = result.msg;
                    }
                    outDom.innerHTML += `${outMsg}<br /><br />`;
                    file = null;
                    state = false;
                    submitDom.disabled = false;
                }
            };
            request.open('POST', '');
            request.send(formData);
        }
    </script>
</body>
</html>
这个源码可以粘贴剪切板的图片也可以选择文件,进行上传。


评论已关闭

Top