PHP实现文件上传至阿里云OSS

请添加图片描述

今天给大家实现一个头像上传功能,需要将文件上传至阿里云的OSS,所以也是百度、谷歌了一番,但都不是很管用,所以自己研究了一番,下面向大家分享这个过程,在这之前先下载阿里云OSS的SDK
文件目录如下
在这里插入图片描述

先拷贝sdk到上传控制器的同级目录

新建一个一个简单的HTML,传递文件到控制器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div style="width: 100%; height: 100%;">
    <form action="upload.php" method="post" enctype="multipart/form-data">
        <label for="file">文件名:</label>
        <input type="file" name="file" id="file"><br>
        <input type="submit" name="submit" value="提交">
    </form>
</div>
</body>
</html>


拷贝sdk中samples目录下的Config.php和Common.php到控制器的统计目录,修改Config.php代码如下

<?php

/**
 * Class Config
 *
 * Make configurations required by the sample.
 * Users can run RunAll.php which runs all the samples after configuring Endpoint, AccessId, and AccessKey.
 */
final class Config
{
    const OSS_ACCESS_ID = 'update me';
    const OSS_ACCESS_KEY = 'update me';
    const OSS_ENDPOINT = 'update me';
    const OSS_TEST_BUCKET = 'update me';
}

第一个填写你的阿里云AccessKey ID,第二个填写你的阿里云secret,这个咋阿里云的AccessKey 管理可以查到,第三个在oss那里可以查到
在这里插入图片描述
第四个是你Bucket的名字应该不用我多说了
Common.php的代码修改引入的代码也就是前面的6行,代码如下:

<?php

if (is_file(__DIR__ . '/aliyun-php-sdk-oss/autoload.php')) {
    require_once __DIR__ . '/aliyun-php-sdk-oss/autoload.php';
}
if (is_file(__DIR__ . '/aliyun-php-sdk-oss/vendor/autoload.php')) {
    require_once __DIR__ . '/aliyun-php-sdk-oss/vendor/autoload.php';
}
require_once __DIR__ . '/Config.php';

use OSS\OssClient;
use OSS\Core\OssException;

/**
 * Class Common
 *
 * The Common class for 【Samples/*.php】 used to obtain OssClient instance and other common functions
 */
class Common
{
    const endpoint = Config::OSS_ENDPOINT;
    const accessKeyId = Config::OSS_ACCESS_ID;
    const accessKeySecret = Config::OSS_ACCESS_KEY;
    const bucket = Config::OSS_TEST_BUCKET;

    /**
     * Get an OSSClient instance according to config.
     *
     * @return OssClient An OssClient instance
     */
    public static function getOssClient()
    {
        try {
            $ossClient = new OssClient(self::accessKeyId, self::accessKeySecret, self::endpoint, false);
        } catch (OssException $e) {
            printf(__FUNCTION__ . "creating OssClient instance: FAILED\n");
            printf($e->getMessage() . "\n");
            return null;
        }
        return $ossClient;
    }

    public static function getBucketName()
    {
        return self::bucket;
    }

    /**
     * A tool function which creates a bucket and exists the process if there are exceptions
     */
    public static function createBucket()
    {
        $ossClient = self::getOssClient();
        if (is_null($ossClient)) exit(1);
        $bucket = self::getBucketName();
        $acl = OssClient::OSS_ACL_TYPE_PUBLIC_READ;
        try {
            $ossClient->createBucket($bucket, $acl);
        } catch (OssException $e) {

            $message = $e->getMessage();
            if (\OSS\Core\OssUtil::startsWith($message, 'http status: 403')) {
                echo "Please Check your AccessKeyId and AccessKeySecret" . "\n";
                exit(0);
            } elseif (strpos($message, "BucketAlreadyExists") !== false) {
                echo "Bucket already exists. Please check whether the bucket belongs to you, or it was visited with correct endpoint. " . "\n";
                exit(0);
            }
            printf(__FUNCTION__ . ": FAILED\n");
            printf($e->getMessage() . "\n");
            return;
        }
        print(__FUNCTION__ . ": OK" . "\n");
    }

    public static function println($message)
    {
        if (!empty($message)) {
            echo strval($message) . "\n";
        }
    }
}

# Common::createBucket();

添加控制器代码,upload.php:

<?php
require_once __DIR__ . '/Common.php';

use OSS\OssClient;

$bucketName = Common::getBucketName();
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);

//******************************* Simple Usage ***************************************************************

//上传图片
$file=$_FILES['file'];
$info = pathinfo($file["name"]);
//文件后缀
$ext = $info['extension'];
//生成文件名称
$file_name = date( "YmdHis" ) . time() . mt_rand(100000,999999) . ".{$ext}" ;
// Upload example.jpg to the specified bucket and rename it to $object.
$res=$ossClient->uploadFile($bucketName,  $file_name,$file["tmp_name"]);
if($res["info"]["http_code"]==200){
    die("上传成功");
}else{
    die("上传失败");
}





登陆阿里云的后台可以查看文件上传上去了没有。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

reg183

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

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

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

打赏作者

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

抵扣说明:

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

余额充值