当前位置:网站首页>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】
Laravel Use Ali OSS+ Alibaba media processing - Ali OSS Official background configuration
Ali OSS The official background creates storage space
First step : preparation
Log in to Ali OSS Console
- establish OSS Storage space

- Follow the steps to create a OSS Storage space

- Create media processing MPS

- 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 Alibaba media processing extension :composer require obacm/aliyun-openapi-mts;( Press enter and wait for the installation to complete )

- 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 !
边栏推荐
- China's smart toy market outlook and investment strategy consulting forecast report from 2022 to 2027
- Excel operation of manual moving average method and exponential smoothing method for time series prediction
- Polarismesh series articles - concept series (I)
- 请指教同花顺是什么软件?在线开户安全么?
- Omni channel member link - tmall member link 3: preparation of member operation content
- 11、 Box styles and user interface
- ctfshow web入门 命令执行web75-77
- 【Redis 系列】redis 学习十六,redis 字典(map) 及其核心编码结构
- CG骨骼动画
- Is it safe to open an account in the top ten securities app rankings in China
猜你喜欢

Spark-day03-core programming RDD operator

International beauty industry giants bet on China

Omni channel member link - tmall member link 3: preparation of member operation content

Flannel's host GW and calico

Scala problem solving the problem of slow SBT Download

HUST网络攻防实践|6_物联网设备固件安全实验|实验二 基于 MPU 的物联网设备攻击缓解技术

科技兴关,荣联与天津海关共建基因组数据库及分析平台
![[graduation season · advanced technology Er] I remember the year after graduation](/img/e7/8e1dafa561217b77a3e3992977a8ec.png)
[graduation season · advanced technology Er] I remember the year after graduation

Redis best practices? If I don't feel excited after reading it, I will lose!!

Microservice governance (nocas)
随机推荐
【Redis 系列】redis 学习十六,redis 字典(map) 及其核心编码结构
Realize microservice load balancing (ribbon)
[probability theory] conditional probability, Bayesian formula, correlation coefficient, central limit theorem, parameter estimation, hypothesis test
Research on the current situation of China's modified engineering plastics market and demand forecast analysis report 2022-2028
11、 Box styles and user interface
Redis cannot connect to the server through port 6379
Pratique de l'attaque et de la défense du réseau HUST | 6 Expérience de sécurité du microprogramme de l'équipement IOT | expérience 2 technologie d'atténuation des attaques de l'équipement IOT basée s
Please advise tonghuashun which securities firm to choose for opening an account? Is it safe to open a mobile account?
Build document editor based on slate
leetcode 715. Range 模块 (hard)
十大券商有哪些?手机开户安全么?
On the use of protostaff [easy to understand]
Current situation investigation and investment prospect forecast analysis report of China's electrolytic copper market from 2022 to 2028
Analysis report on the "fourteenth five year plan" and investment prospect of China's pharmaceutical equipment industry 2022-2028
Several problems encountered in setting up the environment in the past two days
Five strategies and suggestions of member marketing in consumer goods industry
This paper introduces the simple operation of realizing linear quadratic moving average of time series prediction that may be used in modeling and excel
CG骨骼动画
redis通过6379端口无法连接服务器
Scala-day03- operators and loop control