百度的Ueditor(php)上传到aws s3存储方案

1.首先在php文件夹中下载aws-sdk-php通过composer下载

composer require aws/aws-sdk-php

2.在ueditor/php下新建aws_config.php文件

<?php 
    return array(
        "region" => "xxxxxxx",
       "bucket" => "xxxxxxx",
        "accessKeyId" => "xxxxxxx",
        "secretAccessKey" => "xxxxxxx"
    );
?>

3.修改php下的config.json,把图片访问的前缀改成相应的远程访问的前缀

"imageUrlPrefix": "", /* 图片访问路径前缀 */

4.修改主要的上传文件Uploader.class.php头部引入

require ‘vendor/autoload.php‘;
use Aws\Credentials\Credentials;
use Aws\S3\S3Client;
use Aws\S3\MultipartUploader;
use Aws\Exception\MultipartUploadException;

5.在Uploader.class.php中将upFile方法改成如下方法,以及新增一个deldir方法(本来想用@unlink删除临时文件,结果一直无法删除,试过unset,也无法解决,有大佬知道的告知小弟一下)

private function upFile()
    {
        $file = $this->file = $_FILES[$this->fileField];
        if (!$file) {
            $this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND");
            return;
        }
        if ($this->file[‘error‘]) {
            $this->stateInfo = $this->getStateInfo($file[‘error‘]);
            return;
        } else if (!file_exists($file[‘tmp_name‘])) {
            $this->stateInfo = $this->getStateInfo("ERROR_TMP_FILE_NOT_FOUND");
            return;
        } else if (!is_uploaded_file($file[‘tmp_name‘])) {
            $this->stateInfo = $this->getStateInfo("ERROR_TMPFILE");
            return;
        }

        $this->oriName = $file[‘name‘];
        $this->fileSize = $file[‘size‘];
        $this->fileType = $this->getFileExt();
        $this->fullName = $this->getFullName();
        $this->filePath = $this->getFilePath();
        $this->fileName = $this->getFileName();
        $dirname = dirname($this->filePath);

        //检查文件大小是否超出限制
        if (!$this->checkSize()) {
            $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
            return;
        }

        //检查是否不允许的文件格式
        if (!$this->checkType()) {
            $this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED");
            return;
        }

        //创建目录失败
        if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
            $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
            return;
        } else if (!is_writeable($dirname)) {
            $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
            return;
        }

        $info = move_uploaded_file($file["tmp_name"], $this->filePath);
        //移动文件
        if (!($info && file_exists($this->filePath))) { //移动失败
            $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
        } else { //移动成功

            //执行到这里,代表已经完成了上传,此时系统会提示上传成功
            //------------------------------------------------  start  ---------------------------------------------------------
            //上传aws s3
            //设置超时
            set_time_limit(0);
            $config = require_once("aws_config.php");
            $region = $config[‘region‘]; //‘AWS存储桶名称‘;
            $bucket = $config[‘bucket‘]; //仓库名
            $accessKeyId = $config[‘accessKeyId‘];
            $secretAccessKey = $config[‘secretAccessKey‘];
            //证书 AWS access KEY ID  和  AWS secret  access KEY 替换成自己的
            $credentials = new Credentials($accessKeyId, $secretAccessKey);
            //s3客户端
            $s3 = new S3Client([
                  ‘version‘     => ‘latest‘,
                  //地区 亚太区域(新加坡)    
                  //AWS区域和终端节点: http://docs.amazonaws.cn/general/latest/gr/rande.html
                  ‘region‘      => $region,
                  //加载证书
                  ‘credentials‘ => $credentials,
                  //开启bug调试
                  //‘debug‘   => true
            ]);
        
            //需要上传的文件
            //ROOT_PATH项目根目录,文件的本地路径例:D:/www/abc.jpg;
            // $source = ROOT_PATH.$file; 
            // $source = ‘C:/Users/Administrator/Desktop/媒体文件/图片/1.jpg‘;
            $source = $this->filePath;
            //多部件上传
            $uploader = new MultipartUploader($s3, $source, [
                //存储桶
                ‘bucket‘ => $bucket,
                //上传后的新地址
                ‘key‘    => $this->fullName,
                //设置访问权限  公开,不然访问不了
                ‘ACL‘    => ‘public-read‘,
                //分段上传
                ‘before_initiate‘ => function (\Aws\Command $command) {
                    // $command is a CreateMultipartUpload operation
                    $command[‘CacheControl‘] = ‘max-age=3600‘;
                },
                ‘before_upload‘   => function (\Aws\Command $command) {
                    // $command is an UploadPart operation
                    $command[‘RequestPayer‘] = ‘requester‘;
                },
                ‘before_complete‘ => function (\Aws\Command $command) {
                    // $command is a CompleteMultipartUpload operation
                   $command[‘RequestPayer‘] = ‘requester‘;
                },
            ]);
            try {
                $result = $uploader->upload();
                //上传成功--返回上传后的地址
                if($result) {
                    $this->deldir($dirname.‘/‘, $this->fileName);
                    $this->stateInfo = $this->stateMap[0];
                    //file_put_contents("./log/log.txt","\ntime:".time()."  ".json_encode($ret)."\n",FILE_APPEND);
                    // $data = [
                    //    ‘type‘ => ‘1‘,
                    //    ‘data‘ => urldecode($result[‘ObjectURL‘])
                    // ];
                }
            } catch (MultipartUploadException $e) {
               //上传失败--返回错误信息
                if(!is_dir("./log")){
                    if(!mkdir("log",0755,true)){
                        die("当前目录没有写权限");
                    }
                }
                file_put_contents("./log/log.txt","\ntime:".time()."  ".json_encode($_SERVER[‘DOCUMENT_ROOT‘]."/".$this->fullName)."\n",FILE_APPEND);
                $this->stateInfo = $this->getStateInfo("AWS_ERR");
                $uploader =  new MultipartUploader($s3, $source, [
                    ‘state‘ => $e->getState(),
                ]);
                // $data = [
                //   ‘type‘ => ‘0‘,
                //   ‘data‘ =>  $e->getMessage()
                // ];
           }
           // return $data;
           //------------------------------------------------- end   ---------------------------------------------------------
        }
    }
    private function deldir($path, $filename){
        //如果是目录则继续
       if(is_dir($path)){
            //扫描一个文件夹内的所有文件夹和文件并返回数组
            $p = scandir($path);
            foreach($p as $val){
            //排除目录中的.和..
                if($val !="." && $val !=".." && $val != $filename){
                    //如果是目录则递归子目录,继续操作
                    if(is_dir($path.$val)){
                        //子目录中操作删除文件夹和文件
                        deldir($path.$val.‘/‘);
                        //目录清空后删除空文件夹
                        @rmdir($path.$val.‘/‘);
                     } else{
                        //如果是文件直接删除
                        unlink($path.$val);
                    }
                }
            }
        }
    }

6.修改重命名方法,主要是随机数那里抹去两个零就可以了

/**
     * 重命名文件
     * @return string
     */
    private function getFullName()
    {
        //替换日期事件
        $t = time();
        $d = explode(‘-‘, date("Y-y-m-d-H-i-s"));
        $format = $this->config["pathFormat"];
        $format = str_replace("{yyyy}", $d[0], $format);
        $format = str_replace("{yy}", $d[1], $format);
        $format = str_replace("{mm}", $d[2], $format);
        $format = str_replace("{dd}", $d[3], $format);
        $format = str_replace("{hh}", $d[4], $format);
        $format = str_replace("{ii}", $d[5], $format);
        $format = str_replace("{ss}", $d[6], $format);
        $format = str_replace("{time}", $t, $format);

        //过滤文件名的非法自负,并替换文件名
        $oriName = substr($this->oriName, 0, strrpos($this->oriName, ‘.‘));
        $oriName = preg_replace("/[\|\?\"\<\>\/\*\\\\]+/", ‘‘, $oriName);
        $format = str_replace("{filename}", $oriName, $format);

        //替换随机字符串
        $randNum = rand(1, 100000000) . rand(1, 100000000);
        if (preg_match("/\{rand\:([\d]*)\}/i", $format, $matches)) {
            $format = preg_replace("/\{rand\:[\d]*\}/i", substr($randNum, 0, $matches[1]), $format);
        }

        $ext = $this->getFileExt();
        return $format . $ext;
    }

相关推荐