TP5.1 阿里云OSS上传(layui)

插件合集

点击跳转

安装

composer require aliyuncs/oss-sdk-php

基类

<?php
/**
 * Created by PhpStorm.
 * User: ZhangYongFeng
 * Date: 2021/1/5
 * Time: 16:37
 * ━━━━━━━━━神兽出没━━━━━━━━━
 *        ┏┓   ┏┓+ +
 *       ┏┛┻━━━┛┻┓ + +
 *       ┃       ┃  
 *       ┃   ━   ┃ ++ + + +
 *       ████━████ ┃+
 *       ┃       ┃ +
 *       ┃   ┻   ┃
 *       ┃       ┃ + +
 *       ┗━┓   ┏━┛
 *         ┃   ┃           
 *         ┃   ┃ + + + +
 *         ┃   ┃    Code is far away from bug with the animal protecting       
 *         ┃   ┃ +     神兽保佑,代码无bug  
 *         ┃   ┃
 *         ┃   ┃  +         
 *         ┃    ┗━━━┓ + +
 *         ┃        ┣┓
 *         ┃        ┏┛
 *         ┗┓┓┏━┳┓┏┛ + + + +
 *          ┃┫┫ ┃┫┫
 *          ┗┻┛ ┗┻┛+ + + +
 * ━━━━━━━━━感觉萌萌哒━━━━━━━━━
 */


namespace app\base\controller;

use think\App;
use OSS\OssClient;
use OSS\Core\OssUtil;
use OSS\Core\OssException;

/**
 * @title   OSS
 * @desc    OSS上传类
 * Class Oss
 * @package app\base\controller
 */
class Oss extends Base
{
    private $ossConfig;

    public function __construct(App $app = null)
    {
        parent::__construct($app);

        $this->ossConfig = [
            'accessKeyId' => $this->config['cfg_accessKeyId'],
            'accessKeySecret' => $this->config['cfg_accessKeySecret'],
            'endpoint' => $this->config['cfg_endpoint'],
            'bucket' => $this->config['cfg_bucket'],
        ];
    }

    /**
     * 简单上传文件
     * @param string $url  上传到OSS的路径,可自定义
     * @param object $uploadFile 上传的文件
     * @return array ['code' => 1001, 'data' => ['url' => ''], 'msg' => '上传成功']
     * @author zyf <1322816443@qq.com>
     * */
    public function upOssSimple($url, $uploadFile)
    {
        try{
            $ossClient = new OssClient($this->ossConfig['accessKeyId'], $this->ossConfig['accessKeySecret'], $this->ossConfig['endpoint']);
            $result = $ossClient->uploadFile($this->ossConfig['bucket'], $url, $uploadFile);
            if (isset($result['info']['http_code']) AND $result['info']['http_code'] == 200) {
                $data['url'] = $result['info']['url'];
                return parent::showReturnCode(1001, $data, '上传成功');
            }else{
                return parent::showReturnCodeWithOutData(500, 'OSS上传错误');
            }
        } catch(OssException $e) {
            $msg = $e->getMessage();
            return parent::showReturnCodeWithOutData(500, $msg);
        }
    }

    /**
     * 切片上传
     * @param string $url  上传到OSS的路径,可自定义
     * @param object $uploadFile 上传的文件
     * @return array ['code' => 1001, 'data' => ['url' => ''], 'msg' => '上传成功']
     * @author zyf <1322816443@qq.com>
     * */
    public function upOssSection($url, $uploadFile)
    {
        /**
         *  步骤1:初始化一个分片上传事件,获取uploadId。
         */
        try{
            $ossClient = new OssClient($this->ossConfig['accessKeyId'], $this->ossConfig['accessKeySecret'], $this->ossConfig['endpoint']);
            //返回uploadId。uploadId是分片上传事件的唯一标识,您可以根据uploadId发起相关的操作,如取消分片上传、查询分片上传等。
            $uploadId = $ossClient->initiateMultipartUpload($this->ossConfig['bucket'], $url);
        } catch(OssException $e) {
            $msg = $e->getMessage();
            return parent::showReturnCodeWithOutData(500, $msg);
        }
        /*
         * 步骤2:上传分片。
         */
        $partSize = 10 * 1024 * 1024;
        $uploadFileSize = filesize($uploadFile);
        $pieces = $ossClient->generateMultiuploadParts($uploadFileSize, $partSize);
        $responseUploadPart = array();
        $uploadPosition = 0;
        $isCheckMd5 = true;
        foreach ($pieces as $i => $piece) {
            $fromPos = $uploadPosition + (integer)$piece[$ossClient::OSS_SEEK_TO];
            $toPos = (integer)$piece[$ossClient::OSS_LENGTH] + $fromPos - 1;
            $upOptions = array(
                // 上传文件。
                $ossClient::OSS_FILE_UPLOAD => $uploadFile,
                // 设置分片号。
                $ossClient::OSS_PART_NUM => ($i + 1),
                // 指定分片上传起始位置。
                $ossClient::OSS_SEEK_TO => $fromPos,
                // 指定文件长度。
                $ossClient::OSS_LENGTH => $toPos - $fromPos + 1,
                // 是否开启MD5校验,true为开启。
                $ossClient::OSS_CHECK_MD5 => $isCheckMd5,
            );
            // 开启MD5校验。
            if ($isCheckMd5) {
                $contentMd5 = OssUtil::getMd5SumForFile($uploadFile, $fromPos, $toPos);
                $upOptions[$ossClient::OSS_CONTENT_MD5] = $contentMd5;
            }
            try {
                // 上传分片。
                $responseUploadPart[] = $ossClient->uploadPart($this->ossConfig['bucket'], $url, $uploadId, $upOptions);
            } catch(OssException $e) {
                $msg = $e->getMessage();
                return parent::showReturnCodeWithOutData(500, $msg);
            }
        }
        // $uploadParts是由每个分片的ETag和分片号(PartNumber)组成的数组。
        $uploadParts = array();
        foreach ($responseUploadPart as $i => $eTag) {
            $uploadParts[] = array(
                'PartNumber' => ($i + 1),
                'ETag' => $eTag,
            );
        }
        /**
         * 步骤3:完成上传。
         */
        try {
            // 执行completeMultipartUpload操作时,需要提供所有有效的$uploadParts。OSS收到提交的$uploadParts后,会逐一验证每个分片的有效性。当所有的数据分片验证通过后,OSS将把这些分片组合成一个完整的文件。
            $result = $ossClient->completeMultipartUpload($this->ossConfig['bucket'], $url, $uploadId, $uploadParts);
            if (isset($result['info']['http_code']) AND $result['info']['http_code'] == 200) {
                $data['url'] = $result['info']['url'];
                return parent::showReturnCode(1001, $data, '上传成功');
            }else{
                return parent::showReturnCodeWithOutData(500, 'OSS上传错误');
            }
        }  catch(OssException $e) {
            $msg = $e->getMessage();
            return parent::showReturnCodeWithOutData(500, $msg);
        }
    }


}

后端

    public function upOss()
    {
        // 文件名称生成
        $file = request()->file('file');
        $file_name = sha1(date('YmdHis',time()).uniqid()).'.'.pathinfo($file->getInfo()['name'],PATHINFO_EXTENSION);
        // 文件路径生成
        switch($this->param['type']){
            case "1": $file_path = 'software/'; break;
            case "2": break;
            case "3": $file_path = 'manual/'; break;
            case "4": $file_path = 'file/'; break;
        }
        $data =  $this->oss->upOssSection($file_path . date('Ymd') .'/'. $file_name, $file->getInfo()['tmp_name']);
        if($data['code'] == 1001) $data['data']['size'] = trans_byte($file->getInfo()['size']);
        return $data;
    }

HTML

<div class="layui-form-item">
    <label class="layui-form-label">上传:</label>
    <div class="layui-input-block">
        <div class="layui-upload">
            <input type="hidden" name="url" id="url" value="">
            <input type="hidden" name="size" id="size" value="">
            <button type="button" class="layui-btn upload">文件</button>
        </div>
    </div>
</div>

JS

layui.use('upload', function(){
    var upload = layui.upload;
    //执行实例
    upload.render({
        elem: '.upload'
        ,data: { type: $("#type").val() }
        , url: '<{:url(\'upOss\')}>'
        , multiple: false
        , accept: 'file'
        , before: function(obj){ layer.load(1); }
        , done: function (res) {
            layer.msg(res.msg)
            if(res.code == 1001){ $("#url").val(res.data.url); $("#size").val(res.data.size); layer.closeAll('loading'); this.item.html('已上传,点击重传').attr('class', 'layui-btn layui-btn-normal upload') }
        }, error: function(index, upload){ layer.closeAll('loading'); }
    })
});

 

posted @ 2021-01-07 09:06  张永峰z  阅读(950)  评论(1编辑  收藏  举报