当前位置:网站首页>Php+laravel5.7 use Alibaba oss+ Alibaba media to process and upload image / video files

Php+laravel5.7 use Alibaba oss+ Alibaba media to process and upload image / video files

2022-06-26 12:22:00 Special sword

Ali OSS The official background creates storage space

First step : preparation

Log in to Ali OSS Console

  1. establish OSS Storage space
     Log in to Alibaba cloud console
  2. Follow the steps to create a OSS Storage space
     Follow the steps to create storage space
  3. Create media processing MPS
     Create media processing MPS
  4. Use composer Execute the installation OSS Expansion order :composer require aliyuncs/oss-sdk-php; Press down “ Enter key ” Wait for the installation to complete ;
    ( I use phpStom Editor )
     Install Ali oss expand
  5. Install Alibaba media processing extension :composer require obacm/aliyun-openapi-mts;( Press enter and wait for the installation to complete )
     Install Alibaba media processing extension
  6. Upload files to OSS Code ( Here is the official php Upload SDK)
	//OSS Upload controller 
    public function OssUploadFile(Request $request)
    {
        $accessKeyId = " Yours accessKeyId ";
        $accessKeySecret = " Yours  accessKeySecret ";
        // Endpoint Take Beijing for example , Other Region Please fill in according to the actual situation .(‘’http:// Ali OSS Storage space Overview —> Extranet access )
        $endpoint = "http://oss-cn-beijing.aliyuncs.com";
        //  Storage space name 
        $bucket = " Yours bucket name ";

        // front end inupt The name of the form 
        $file_name_A = 'file_video';
        //laravel  Get the upload file 
        $tmpFile_A = $request->file($file_name_A);
        // Generate upload OSS The path after + file name ( Be careful : The path is forbidden to use "/" start )
        $object_A = 'aa/'.date("Y_M_D_H_M_S") . '.' . $tmpFile_A->getClientOriginalExtension();
        //  Get temporary files 
        $filePath_A = $tmpFile_A->getPath() . '/' . $tmpFile_A->getFilename();
        //OssClient
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        $info_A = $ossClient->uploadFile($bucket, $object_A, $filePath_A);// To get the uploaded file information 
        // Judge whether the upload is successful  $info_A['oss-request-url'] : Get the uploaded OSS Access address 
        if($info_A['oss-request-url']){
            # Upload successful 
            var_dump(' Upload successful ');
            die();
        }else{
            # Upload failed 
            var_dump(' Upload failed ');
            die();
        }
    }

7 Use OSS Upload + Transcoding function ( Uploading the code is the first... Above 6 Step );

	//OSS Upload controller 
    public function OssUploadFile(Request $request)
    {
        $accessKeyId = " Yours accessKeyId ";
        $accessKeySecret = " Yours accessKeySecret  ";
        // Endpoint Take Beijing for example , Other Region Please fill in according to the actual situation .
        $endpoint = "http://oss-cn-beijing.aliyuncs.com";
        //  Storage space name 
        $bucket = "bingtanghulu";

        // front end inupt The name of the form 
        $file_name_A = 'file_video';
        //laravel  Get the upload file 
        $tmpFile_A = $request->file($file_name_A);
        // Generate upload OSS The path after + file name ( Be careful : The path is forbidden to use "/" start )
        $object_A = 'aa/'.date("Y_M_D_H_M_S") . '.' . $tmpFile_A->getClientOriginalExtension();
        //  Get temporary files 
        $filePath_A = $tmpFile_A->getPath() . '/' . $tmpFile_A->getFilename();
        //OssClient
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        $info_A = $ossClient->uploadFile($bucket, $object_A, $filePath_A);// To get the uploaded file information 
        // Judge whether the upload is successful 
        if($info_A['oss-request-url']){
            # Upload successful 
            //dd(' Upload successful ');
            # Call transcoding 
            $this->OssMts($object_A);
        }else{
            # Upload failed 
            dd(' Upload failed ');
        }
    }

    /**
     *  Alibaba cloud media processing — transcoding 
     * 2019/10/13/22:20
     * @param $oss_input_object_name :OSS File name that needs transcoding in , Such as 'Test/input_video001.mp4'
     */
    private function OssMts($oss_input_object_name){
        # Transcoding public parameter configuration area 
        $access_key_id = ' Yours accessKeyId';
        $access_key_secret = ' Yours access_key_secret ';
        // What you need to do OSS Location of storage space , for example 'cn-beijign' Express ‘ Beijing China ’
        $mps_region_id = 'cn-beijing';

        $pipeline_id = ' Your pipeline ID';// The Conduit ID(// Your case media processing console -> Global settings -> The Conduit -> The Conduit ID)
        $template_id = 'S00000001-200010';// Templates ID( Official documents Deom The default , You handle it yourself in the media -> Global settings -> You can also create one in the transcoding template , If you don't, just use the official Demo Give this , Or popularize science by oneself )

        $oss_location = 'oss-cn-beijing';// What you need to do OSS The location of the storage space is OSS Storage space Overview -> Extranet access EndPoint( Regional nodes ) The prefix of ,( Mine is Beijing , So write 'oss-cn-beijing')
        $oss_bucket = ' Yours bucket name ';// Yours Oss Storage space bucket name 


        // File to be transcoded ( After the previous upload method succeeds , Call the parameter passed in by transcoding method )
        $oss_input_object = $oss_input_object_name;
        // The file name output after transcoding ( You can also add your own path , for example :‘test/2020-02-11/output.mp4’  Oss The storage space will create its own file hierarchy according to your local path , Remember that the beginning of the file path cannot be used ‘/’ perhaps ‘\’ start , This oss When you create a folder manually, you will be prompted )
        $oss_output_object = 'output.mp4';

        $clientProfile = DefaultProfile::getProfile(
            $mps_region_id,                   #  Your  Region ID
            $access_key_id,                   #  Your  AccessKey ID
            $access_key_secret                #  Your  AccessKey Secret
        );

		// Start transcoding 
        $client = new DefaultAcsClient($clientProfile);
		 #  establish API Request and set parameters 
        $request = new SubmitJobsRequest();
        $request->setAcceptFormat('JSON');
        # Input  Enter the... To be transcoded OSS file 
        $input = [
            'Location' => $oss_location,
            'Bucket' => $oss_bucket,
            'Object' => urlencode($oss_input_object)
        ];
        $request->setInput(json_encode($input));
        # Output  Output transcoding finished OSS file 
        $output = [
            'OutputObject' => urlencode($oss_output_object)
        ];
        # Ouput->Container  Format after transcoding 
        $output['Container'] = array('Format' => 'mp4');
        # Ouput->Video  Enter the video configuration 
        // Parameters in this array value  Define yourself according to your actual needs 
        $output['Video'] = [
            'Codec' =>'H.264',// Coding format 
            'Bitrate' => 1500,// Bit rate / Bit rate 
            'Width' => 1280,// Video width 
            'Fps' => 25// Video frames per second 
        ];
        # Ouput->Audio  Input audio configuration 
         // Parameters in this array value  Define yourself according to your actual needs 
        $output['Audio'] = [
            'Codec' => 'AAC',// decoder 
            'Bitrate' => 128,// Bit rate 
            'Channels' => 2,// channel 
            'Samplerate' => 44100// Sampling rate 
        ];
        # Ouput->TemplateId // Input templating 
        $output['TemplateId'] = $template_id;
        $outputs = array($output);
        # Set output 
        $request->setOUtputs(json_encode($outputs));
        # Set input OSS_Bucket name 
        $request->setOutputBucket($oss_bucket);
        # Set input OSS_ home 
        $request->setOutputLocation($oss_location);
        # PipelineId  Set transcoding pipeline ID
        $request->setPipelineId($pipeline_id);
        #  Initiate the request and process the return 
        $response = $client->getAcsResponse($request);
        // Judge whether transcoding is successful 
        if($response->{'JobResultList'}->{'JobResult'}[0]->{'Success'}){
            # Transcoding succeeded 
            // Delete non transcoded source files 
            // Splice the transcoded file path and update the database 
        }else{
            # Transcoding failed 
            'SubmitJobs Failed code:' .
            $response->{'JobResultList'}->{'JobResult'}[0]->{'Code'} .
            ' message:' .
            $response->{'JobResultList'}->{'JobResult'}[0]->{'Message'} . "\n";
        }

        #  Initiate the request and process the return , The following points can capture exceptions according to your needs , This is what allows you to read error reports and return values .
        try {
            $response = $client->getAcsResponse($request);
            print 'RequestId is:' . $response->{'RequestId'} . "\n";
            //RequestId is:9EF6A44A-7568-407F-B48C-A6A840C83ECE JobId is:5328efd028dc458da5c5fdb9bee7a245  This is the return value 
            if ($response->{'JobResultList'}->{'JobResult'}[0]->{'Success'}) {
                print 'JobId is:' .
                    $response->{'JobResultList'}->{'JobResult'}[0]->{'Job'}->{'JobId'} . "\n";
            } else {
                print 'SubmitJobs Failed code:' .
                    $response->{'JobResultList'}->{'JobResult'}[0]->{'Code'} .
                    ' message:' .
                    $response->{'JobResultList'}->{'JobResult'}[0]->{'Message'} . "\n";
            }
        } catch(\ServerException $e) {
            print 'Error: ' . $e->getErrorCode() . ' Message: ' . $e->getMessage() . "\n";
        } catch(\ClientException $e) {
            print 'Error: ' . $e->getErrorCode() . ' Message: ' . $e->getMessage() . "\n";
        }

    }

That's all Laravel 5.7 +php Use Alibaba official upload SDK and composer Download the detailed usage of Alibaba media processing expansion .

Note that there are many configuration items in the above code , for example accessKeyId and accessKeyId And so on. I didn't encapsulate them in the demonstration , In actual production , I will encapsulate this information into config in . In the use of laravel Auxiliary function config(‘key’) To call !

原网站

版权声明
本文为[Special sword]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202170522214958.html

随机推荐