原生的异步上传文件表单

觉得还蛮实用的,就发这里了。不需要什么包,跟框架也无关,直接复制粘贴,拿来用就行

html端

<input type="file" class="form-control" id="input-syncFile"
accept=".pem, .pem"
>
<input type="text" class="form-control" name="options[sync]" id="input-sync"
name="options[sync]"  readonly="readonly"
value="">
<input type="file" class="form-control" id="input-syncFile2File"
accept=".pem, .pem"
>
<input type="text" class="form-control" id="input-syncFile2"
name="options[syncFile2]" readonly="readonly"
value="{$site_info.syncFile2|default=''}"
>
<script>
    document.getElementById('input-syncFile').addEventListener('change', function () {
        var img = this.files[0];
        uploadImage('sync', img, '/admin/setting/uploadsync', function (url) {
            document.getElementById('input-sync').setAttribute('value',url);
        });
        getBase64ImageUrl(img, function (base64ImageUrl) {
            var height = 100,
                width = 100;
            getThumbnail(base64ImageUrl, height, width, function (base64ThumbnailUrl) {
                setImageUrl(base64ThumbnailUrl);
            })
        });
    }, false);
    document.getElementById('input-syncFile2File').addEventListener('change', function () {
        var img = this.files[0];
        uploadImage('syncFile2', img, '/admin/setting/uploadsync', function (url) {
            document.getElementById('input-syncFile2').setAttribute('value',url);
        });
        getBase64ImageUrl(img, function (base64ImageUrl) {
            var height = 100,
                width = 100;
            getThumbnail(base64ImageUrl, height, width, function (base64ThumbnailUrl) {
                setImageUrl(base64ThumbnailUrl);
            })
        });
    }, false);
    function setImageUrl(url) {
        document.getElementById('preview').setAttribute('src', url);
    };
    function uploadImage(name, img, url, callback) {
        var xhr = new XMLHttpRequest();
        var fd = new FormData();
        xhr.open("POST", url, true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                callback && callback(xhr.responseText);
            }
        };
        fd.append(name, img);
        fd.append("name", name);
        xhr.send(fd);
    };
    function getBase64ImageUrl(img, callback) {
        var reader = new FileReader();
        reader.readAsDataURL(img);
        reader.onload = function () {
            callback && callback(reader.result);
        };
        reader.onerror = function (error) {
            console.log('Error: ', error);
        };
    };
    function getThumbnail(base64ImageUrl, height, width, callback) {
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext("2d");
        var image = new Image();
        image.src = base64ImageUrl;
        image.onload = function () {
            ctx.drawImage(image, 0, 0, width, height);
            callback && callback(canvas.toDataURL());
        };
    }  
</script>

php端


    public function uploadsync(){
        $file = $_POST['name'];
        try{
            if($file == 'sync'){
                if ($_FILES["sync"]["error"] > 0)
                {
                    throw new \RuntimeException("错误:" . $_FILES["sync"]["error"] . "<br>");
                }
                $temp = $_FILES['sync']['tmp_name'];
                $path = '/1634478851_20221111_cert/'.date('YmdHis').'apiclient_key.pem';
            }
            if($file == 'syncFile2'){
                if ($_FILES["syncFile2"]["error"] > 0)
                {
                    throw new \RuntimeException("错误:" . $_FILES["syncFile2"]["error"] . "<br>");
                }
                $temp = $_FILES['syncFile2']['tmp_name'];
                $path = '/1634478851_20221111_cert/'.date('YmdHis').'wechatpay.pem';
            }  

            move_uploaded_file($temp, CMF_ROOT.'public'.$path);
        }
        catch(\Exception $e){
            return $e->getMessage().$e->getLine().$e->getTraceAsString();
        }
        return $path;
    }
本作品采用《CC 协议》,转载必须注明作者和本文链接
reading
白小二
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!