php 使用base64方式上传图片

控制器代码

 public function doTest(){
        if($this->_request->isPost()) {

            $base64_img = trim($_POST['img']);
            $up_dir = './img/';//存放在当前目录的upload文件夹下

            if(!file_exists($up_dir)){
                mkdir($up_dir,0777);
            }

            if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)){
                $type = $result[2];
                if(in_array($type,array('pjpeg','jpeg','jpg','gif','bmp','png'))){
                    $new_file = $up_dir.date('YmdHis_').'.'.$type;
                    if(file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))){
                        $img_path = str_replace('../../..', '', $new_file);
                        echo '图片上传成功</br>![](' .$img_path. ')';
                    }else{
                        echo '图片上传失败</br>';

                    }
                }else{
                    //文件类型错误
                    echo '图片上传类型错误';
                }

            }else{
                //文件错误
                echo '文件错误';
            }

        }else{
            $view = $this->initView();
            $view->render('agreement/test.php');
        }
    }

php页面代码

<div class="primary">

    <form action="<?php echo $this->url('action=test');?>" method="post">
        <input type="file" value="sdgsdg" id="demo_input" />
        <textarea name="img" id="result" rows=30 cols=300></textarea>
        <p id="img_area"></p>
        <input type="submit" value="提交">
    </form>
</div>


    <script>
    window.onload = function(){
        var input = document.getElementById("demo_input");
        var result= document.getElementById("result");
        var img_area = document.getElementById("img_area");
        if ( typeof(FileReader) === 'undefined' ){
            result.innerHTML = "抱歉,你的浏览器不支持 FileReader,请使用现代浏览器操作!";
            input.setAttribute('disabled','disabled');
        }else{
            input.addEventListener('change',readFile,false);
        }
    }
    function readFile(){
        var file = this.files[0];
        //这里我们判断下类型如果不是图片就返回 去掉就可以上传任意文件
        if(!/image\/\w+/.test(file.type)){
            alert("请确保文件为图像类型");
            return false;
        }
        var reader = new FileReader();
        reader.readAsDataURL(file);
        console.log();
        reader.onload = function(e){
            result.innerHTML = this.result;
            img_area.innerHTML = '<div class="sitetip">图片img标签展示:</div>![]('+this.result+')';
        }
    }
    </script>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
ThinkPHP 是一款流行的 PHP 框架,它提供了丰富的功能和便利的API来处理文件上传。将Base64编码的图片上传到服务器,你可以按照以下步骤操作: 1. **解码Base64字符串:** 首先,你需要将Base64编码的图片数据转换回原始二进制格式。这可以通过PHP内置的`base64_decode()`函数完成。 ```php $data = base64_decode($base64ImageString); ``` 2. **获取文件名或随机生成:** 为上传的文件创建一个唯一的文件名,可以使用当前时间戳或者随机字符串。 ```php $filename = time() . '_' . md5(rand(0, 999999)) . '.jpg'; ``` 3. **设置临时保存路径:** 在服务器上设置一个临时目录来存储上传的文件,直到正式保存到目标位置。 ```php $tmpPath = '/path/to/your/upload/temporary/directory/'; $tmpFile = $tmpPath . $filename; ``` 4. **保存文件:** 使用PHP的`file_put_contents()`函数将解码后的二进制数据写入临时文件。 ```php file_put_contents($tmpFile, $data); ``` 5. **调用ThinkPHP的上传方法:** ThinkPHP提供了`upload()`方法,用于处理文件上传,包括验证、移动文件等。在这个方法中,指定临时目录和目标目录(通常是public/upload目录)。 ```php $upload = new \Think\File\Upload(); $upload->save(array( 'rootPath' => 'public/upload/', 'tempName' => $tmpFile, 'saveName' => $filename, 'maxSize' => 1048576 // 设置最大上传文件大小 )); ``` 6. **检查上传结果:** `upload()`方法会返回一个包含上传信息的数组,检查`status`字段是否为0(成功)。 ```php if ($upload['status'] == 0) { // 上传成功,将文件移动到目标位置 $targetFile = $upload['savePath'] . $upload['saveName']; rename($tmpFile, $targetFile); } else { // 处理上传失败的情况 } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

reg183

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值