代码改变世界

php 上传视频到阿里云OSS (不用SDK)

2025-09-15 14:08  天心PHP  阅读(8)  评论(0)    收藏  举报
/**
 * 阿里云OSS视频上传类(不使用SDK)
 */
class AliyunOSSUploader
{
    private $accessKeyId;
    private $accessKeySecret;
    private $bucket;
    private $endpoint;

    public function __construct() {
        $this->accessKeyId = '您的AccessKey ID';
        $this->accessKeySecret = '您的AccessKey Secret';
        $this->bucket = '您的Bucket名称';
        $this->endpoint = '您的endpoint';
    }

    /**
     * 生成签名
     */
    private function sign($stringToSign) {
        return base64_encode(hash_hmac('sha1', $stringToSign, $this->accessKeySecret, true));
    }

    /**
     * 生成GMT时间
     */
    private function gmtDate() {
        return gmdate('D, d M Y H:i:s') . ' GMT';
    }

    /**
     * 上传文件
     */
    public function uploadFile($file_path,$file_type, $oss_path) {
        // 读取文件内容
        $content = file_get_contents($file_path);
        $file_size = filesize($file_path);

        // 生成请求头
        $date = $this->gmtDate();
        $content_type = $this->getMimeTypeNew($file_type);

        // 生成签名字符串
        $sign_string = "PUT\n\n" . $content_type . "\n" . $date . "\n/" . $this->bucket . '/' . $oss_path;

        $signature = $this->sign($sign_string);

        // 构建请求头
        $headers = array(
            'Host: ' . $this->bucket . '.' . $this->endpoint,
            'Date: ' . $date,
            'Content-Type: ' . $content_type,
            'Content-Disposition: ' . 'inline',
            'Content-Length: ' . $file_size,
            'Authorization: OSS ' . $this->accessKeyId . ':' . $signature
        );

        // 构建URL
        $url = 'http://' . $this->bucket . '.' . $this->endpoint . '/' . $oss_path;

        // 发送PUT请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_PUT, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_INFILE, fopen($file_path, 'r'));
        curl_setopt($ch, CURLOPT_INFILESIZE, $file_size);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return array('code'=>$http_code,'url'=>$url,'response'=>$response);
    }

    /**
     * 删除视频
     */
    public function deleteOssObject($object) {
        // 构造URL
        $url = "https://{$this->bucket}.{$this->endpoint}/" . ($object);
        // 生成日期时间(GMT格式)
        $date = $this->gmtDate();
        // 构造签名字符串
        $sign_string = "DELETE\n\n\n{$date}\n/{$this->bucket}/{$object}";
        // 计算签名(使用HMAC-SHA1)
        //$signature = base64_encode(hash_hmac('sha1', $sign_string, $this->accessKeySecret, true));
        $signature = $this->sign($sign_string);
        // 构造Authorization头
        $authorization = "OSS {$this->accessKeyId}:{$signature}";
        // 初始化cURL
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "Date: {$date}",
            "Authorization: {$authorization}"
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        // 执行请求
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);

        // 检查响应
        if ($httpCode == 204) {
            return true; // 删除成功
        } else {
            return "删除失败,HTTP状态码: {$httpCode},响应: {$response}";
        }
    }

    /**
     * 获取文件MIME类型
     */
    private function getMimeType($filename) {
        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        $mime_types = array(
            'mp4' => 'video/mp4',
            'avi' => 'video/x-msvideo',
            'mov' => 'video/quicktime',
            'wmv' => 'video/x-ms-wmv',
            'flv' => 'video/x-flv',
            'webm' => 'video/webm',
            // 添加更多类型...
        );

        return isset($mime_types[$ext]) ? $mime_types[$ext] : 'application/octet-stream';
    }

    private function getMimeTypeNew($filename) {
        $mime_types = array(
            'video/mp4' => 'video/mp4',
            'video/x-msvideo' => 'video/x-msvideo',
            'video/quicktime' => 'video/quicktime',
            'video/x-ms-wmv' => 'video/x-ms-wmv',
            'video/x-flv' => 'video/x-flv',
            'video/webm' => 'video/webm',
            // 添加更多类型...
        );
        return isset($mime_types[$filename]) ? $mime_types[$filename] : 'application/octet-stream';
    }
}

//上传使用案例

<?php
//上传
if ($_FILES && $_FILES['video_file']) {
    $uploader = new AliyunOSSUploader();
    
    $upload_file = $_FILES['video_file'];
    $oss_filename = 'videos/' . date('Ymd') . '/' . uniqid() . '.' . 
                   pathinfo($upload_file['name'], PATHINFO_EXTENSION);
                   
    $res = $uploader->uploadFile($upload_file['tmp_name'],$upload_file['type'], $oss_filename);
    print_r('<pre>');
    print_r($res);
    print_r('</pre>');
    exit(); 
}
?>
<form method="post" enctype="multipart/form-data">
    <input type="file" name="video_file" accept="video/*">
    <input type="submit" value="上传视频">
</form>

//删除

//删除 http://usimage.oss-us-west-1.aliyuncs.com/upload/video/cs111/68c7c6ee7fab4.mp4?1757923068
$uploader = new AliyunOSSUploader(); $fla = $uploader->deleteOssObject('upload/video/cs111/68c7c6ee7fab4.mp4'); print_r('<pre>'); print_r($res); print_r('</pre>'); exit();