PHP教程

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

本文主要是介绍PHP实现文件上传至阿里云OSS,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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

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

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

<html>
<head>
<meta charset="utf-8">
<title>上传图片</title>
</head>
<body>
<div style="width: 100%; height: 100%;">
<form action="控制器地址" 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>

拷贝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();

添加控制器代码:

<?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("上传失败");
}



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

这篇关于PHP实现文件上传至阿里云OSS的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!