[教程] 文件上传 OSS 三部曲(三)

最近在做这个新闻模块,编辑新闻的实现采用了ueditor富文本编辑器。
因为ueditor支持服务器本地存储上传文件(在新闻主题中插入的图片),和七牛云OSS存储,并不支持阿里云OSS存储,由于项目依托在阿里云的各种服务上,便于一个账号管理使用的阿里云OSS,没有使用七牛云,此时就需要我们的一些动手能力,给ueditor集成上对aliyunOSS的支持。
首先下载ueditor
在这里没有使用组件化开发,因为富文本编辑器一般不会有什么巨大的漏洞,用户能实现常用的编辑文字和添加样式的功能即可。只需在页面引入几个js文件即可使用。
示例:

1.blade模板载入编辑器

<script type="text/javascript" charset="utf-8" src="{{asset('ueditor/ueditor.config.js')}}"></script>
<script type="text/javascript" charset="utf-8" src="{{asset('ueditor/ueditor.all.min.js')}}"> </script>
<script id="content" name="content" type="text/plain">
@if(!empty($new))
{!! $new->content !!}
@endif
</script>
<!-- 实例化编辑器 -->
<script type="text/javascript">
UE.getEditor('content',{
initialFrameWidth : 800,
initialFrameHeight : 400,

});
var ue = UE.getEditor('content');
</script>

将你编辑后需要保存的的内容添加name属性在id=content的<script>标签内。

2.配置

查看ueditor的./php/目录可知Uploader.class.php是它的上传文件工具类。对其进行改造。

 /**
     * 上传文件的主处理方法
     * @return mixed
     */
    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;
        // }
        //
        // //移动文件
        // if (!(move_uploaded_file($file["tmp_name"], $this->filePath) && file_exists($this->filePath))) { //移动失败
        //     $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
        // } else { //移动成功
        //     $this->stateInfo = $this->stateMap[0];
        // }
        //        include_once('../../../app/Services/oss.php');
        //        \App\Services\OSS::upload($osspath, $serverpath);
        include_once("oss.php");
        //取得临时地址
        $serverpath = $file["tmp_name"];
        //获得文件类型
        $titles = $this->fileType;
        //拼接文件名
        $key = time() . rand(10000, 99999999) .$titles;
        //上传文件夹路径
        $osspath = "news/content/" . $key;
        //上传结果
        $result = OSS::upload($osspath, $serverpath);
        //拼接url
        $this->fullName = 'http://yourself-bucket-name.oss-cn-beijing.aliyuncs.com/'.$osspath;
        //判断结果,给定返回值。
        if ($result) {
            $this->stateInfo = $this->stateMap[0];
            } else {
            $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
        }
                //上传后,删除临时文件
       /* @unlink($file["tmp_name"]);*/
    }

此处要注意修改并维持页面回调当前上传文件的各项信息getFileInfo()方法内的参数。

3.添加oss.php

在php的目录下新建oss.php文件,给ueditor添加阿里云oss的支持。

<?php
/*
  time: 2016-12-30
  author: 马闯
  blog: martist.cn
*/
require_once('../../../vendor/autoload.php');

use JohnLui\AliyunOSS\AliyunOSS;

class OSS
{

    private $ossClient;
    private static $bucketName;
    public $ossServer = 'http://oss-cn-beijing.aliyuncs.com';                   // 外网
    public $ossServerInternal = 'http://oss-cn-beijing-internal.aliyuncs.com';       // 内网
    public $AccessKeyId = 'wwwwwwwwwwww';                      // key
    public $AccessKeySecret = 'wwwwwwwwwwwww';          // secret
    public $BucketName = 'bucket';                // bucket
    public function __construct($isInternal = false)
    {
        $serverAddress = $isInternal ? $this -> ossServerInternal : $this -> ossServer;
        $this->ossClient = AliyunOSS::boot(
            $serverAddress,
            $this -> AccessKeyId,
            $this -> AccessKeySecret
        );
    }

    public static function upload($ossKey, $filePath)
    {
        $oss = new OSS(false); // 上传文件使用内网,免流量费
        $oss->ossClient->setBucket('weiyuyan');
        $res = $oss->ossClient->uploadFile($ossKey, $filePath);
        return $res;
    }

    /**
     * 直接把变量内容上传到oss
     * @param $osskey
     * @param $content
     */
    public static function uploadContent($osskey, $content)
    {
        $oss = new OSS(false); // 上传文件使用内网,免流量费
        $oss->ossClient->setBucket($this -> BucketName);
        $oss->ossClient->uploadContent($osskey, $content);

    }

    /**
     * 删除存储在oss中的文件
     *
     * @param string $ossKey 存储的key(文件路径和文件名)
     * @return
     */
    public static function deleteObject($ossKey)
    {
        $oss = new OSS(false); // 上传文件使用内网,免流量费

        return $oss->ossClient->deleteObject($this -> BucketName, $ossKey);
    }

    /**
     * 复制存储在阿里云OSS中的Object
     *
     * @param string $sourceBuckt 复制的源Bucket
     * @param string $sourceKey - 复制的的源Object的Key
     * @param string $destBucket - 复制的目的Bucket
     * @param string $destKey - 复制的目的Object的Key
     * @return Models\CopyObjectResult
     */
    public function copyObject($sourceBuckt, $sourceKey, $destBucket, $destKey)
    {
        $oss = new OSS(true); // 上传文件使用内网,免流量费

        return $oss->ossClient->copyObject($sourceBuckt, $sourceKey, $destBucket, $destKey);
    }

    /**
     * 移动存储在阿里云OSS中的Object
     *
     * @param string $sourceBuckt 复制的源Bucket
     * @param string $sourceKey - 复制的的源Object的Key
     * @param string $destBucket - 复制的目的Bucket
     * @param string $destKey - 复制的目的Object的Key
     * @return Models\CopyObjectResult
     */
    public function moveObject($sourceBuckt, $sourceKey, $destBucket, $destKey)
    {
        $oss = new OSS(true); // 上传文件使用内网,免流量费

        return $oss->ossClient->moveObject($sourceBuckt, $sourceKey, $destBucket, $destKey);
    }

    public static function getUrl($ossKey)
    {
        $oss = new OSS();
        $oss->ossClient->setBucket($this -> BucketName);
        return $oss->ossClient->getUrl($ossKey, new \DateTime("+1 day"));
    }

    public static function createBucket($bucketName)
    {
        $oss = new OSS();
        return $oss->ossClient->createBucket($bucketName);
    }

    public static function getAllObjectKey($bucketName)
    {
        $oss = new OSS();
        return $oss->ossClient->getAllObjectKey($bucketName);
    }

    /**
     * 获取指定Object的元信息
     *
     * @param  string $bucketName 源Bucket名称
     * @param  string $key 存储的key(文件路径和文件名)
     * @return object 元信息
     */
    public static function getObjectMeta($bucketName, $osskey)
    {
        $oss = new OSS();
        return $oss->ossClient->getObjectMeta($bucketName, $osskey);
    }

}

ok ! 这样便实现了在ueditor中集成阿里云oss文件上传的功能。
Thanks

是非之外有一座花园,我们会在那里相遇
本帖已被设为精华帖!
本帖由 Summer 于 7年前 加精
Martist
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 2
Destiny

666

7年前 评论
dividez

6666666666

7年前 评论

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