当前位置:网站首页>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 !
边栏推荐
- Investment forecast and development strategy analysis report of China's rural sewage treatment industry in 2022
- Lintcode 130 · 堆化
- Ctrip ticket app KMM cross end kV repository mmkv kotlin | open source
- 【毕业季·进击的技术er】忆毕业一年有感
- Consumer goods enterprises, four pain points of member marketing
- Polarismesh series articles - concept series (I)
- 这两天搭建环境遇到的几个问题
- 利用 Repository 中的方法解决实际问题
- 24 database interview questions that must be mastered!
- Redis cannot connect to the server through port 6379
猜你喜欢

This executeQuery (SQL) cannot compile classes for JSP. What is the reason?
![Random numbers in leetcode 710 blacklist [random numbers] the leetcode path of heroding](/img/58/2a56c5c9165295c830082f8b05dd98.png)
Random numbers in leetcode 710 blacklist [random numbers] the leetcode path of heroding

Basic principle of MOS tube and important knowledge points of single chip microcomputer

Scala-day06- pattern matching - Generic

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

【毕业季·进击的技术er】忆毕业一年有感

Pre knowledge of hash table -- binary search tree

量化初级 -- akshare获得股票代码,最简策略

Statistical genetics: Chapter 2, the concept of statistical analysis

SQL injection in Pikachu shooting range
随机推荐
Scala problem solving the problem of slow SBT Download
Five trends of member marketing of consumer goods enterprises in the future
VMware virtual machine bridging mode can not access the campus network "suggestions collection"
PolarisMesh系列文章——概念系列(一)
Five trends of member management in 2022
Leetcode 78. Subset and 90 Subset II
HUST network attack and defense practice | 6_ IOT device firmware security experiment | Experiment 3 freertos-mpu protection bypass
Vulnerability scanning and reverse osmosis of Internet anti artifact
利用 Repository 中的方法解决实际问题
2022 edition of Beijing 5g industry investment planning and development prospect forecast analysis report
CG骨骼动画
菜鸟实战UML——活动图
fastjson的JSONArray和JSONObject[通俗易懂]
Quantitative elementary -- akshare obtains stock code, the simplest strategy
Which is safer and better for great wisdom to open an account
One click deployment of your own community forum
Refined operation, extending the full life cycle value LTV
Excel operation of manual moving average method and exponential smoothing method for time series prediction
Oracle锁表查询和解锁方法
webgame开发中的文件解密