search
HomeBackend DevelopmentPHP Tutorial在 Laravel 5 中集成七牛云存储实现云存储功能

本 扩展包 基于 https://github.com/qiniu/php-sdk 开发,是七牛云储存Laravel 5Storage版,通过本扩展包可以在Laravel 5中集成七牛云存储功能。

1、安装配置

使用之前,先通过Composer安装:

composer require zgldh/qiniu-laravel-storage

然后在 config/app.php 中注册服务提供者:

zgldh\QiniuStorage\QiniuFilesystemServiceProvider::class

接下来在 config/filesystems.php 里的 disks 中新增如下选项:

'disks' => [        ... ,        'qiniu' => [            'driver'  => 'qiniu',            'domains' => [                'default'   => 'laravelacademy.com1.z0.glb.clouddn.com', //你的七牛域名                'https'     => 'dn-laravelacademy.qbox.me',         //你的HTTPS域名                'custom'    => 'static.laravelacademy.org',     //你的自定义域名             ],            'access_key'=> '',  //AccessKey            'secret_key'=> '',  //SecretKey            'bucket'    => '',  //Bucket名字            'notify_url'=> '',  //持久化处理回调地址        ],    ],

2、使用

第一种用法:

$disk = \Storage::disk('qiniu');$disk->exists('file.jpg');                      //文件是否存在$disk->get('file.jpg');                         //获取文件内容$disk->put('file.jpg',$contents);               //上传文件$disk->prepend('file.log', 'Prepended Text');   //附加内容到文件开头$disk->append('file.log', 'Appended Text');     //附加内容到文件结尾$disk->delete('file.jpg');                      //删除文件$disk->delete(['file1.jpg', 'file2.jpg']);$disk->copy('old/file1.jpg', 'new/file1.jpg');  //复制文件到新的路径$disk->move('old/file1.jpg', 'new/file1.jpg');  //移动文件到新的路径$size = $disk->size('file1.jpg');               //取得文件大小$time = $disk->lastModified('file1.jpg');       //取得最近修改时间 (UNIX)$files = $disk->files($directory);              //取得目录下所有文件$files = $disk->allFiles($directory);               //这个没实现。。。$directories = $disk->directories($directory);      //这个也没实现。。。$directories = $disk->allDirectories($directory);   //这个也没实现。。。$disk->makeDirectory($directory);               //这个其实没有任何作用$disk->deleteDirectory($directory);             //删除目录,包括目录下所有子文件子目录$disk->getDriver()->uploadToken('file.jpg');                //获取上传Token$disk->getDriver()->downloadUrl('file.jpg');                //获取下载地址$disk->getDriver()->downloadUrl('file.jpg', 'https');       //获取HTTPS下载地址$disk->getDriver()->privateDownloadUrl('file.jpg');         //获取私有bucket下载地址$disk->getDriver()->privateDownloadUrl('file.jpg', 'https');//获取私有bucket的HTTPS下载地址$disk->getDriver()->imageInfo('file.jpg');                  //获取图片信息$disk->getDriver()->imageExif('file.jpg');                  //获取图片EXIF信息$disk->getDriver()->imagePreviewUrl('file.jpg','imageView2/0/w/100/h/200');                         //获取图片预览URL$disk->getDriver()->persistentFop('file.flv','avthumb/m3u8/segtime/40/vcodec/libx264/s/320x240');   //执行持久化数据处理$disk->getDriver()->persistentFop('file.flv','fop','队列名');   //使用私有队列执行持久化数据处理$disk->getDriver()->persistentStatus($persistent_fop_id);       //查看持久化数据处理的状态。

第二种用法 (就是省略了一个getDriver):

use zgldh\QiniuStorage\QiniuStorage;$disk = QiniuStorage::disk('qiniu');$disk->exists('file.jpg');                      //文件是否存在$disk->get('file.jpg');                         //获取文件内容$disk->put('file.jpg',$contents);               //上传文件$disk->prepend('file.log', 'Prepended Text');   //附加内容到文件开头$disk->append('file.log', 'Appended Text');     //附加内容到文件结尾$disk->delete('file.jpg');                      //删除文件$disk->delete(['file1.jpg', 'file2.jpg']);$disk->copy('old/file1.jpg', 'new/file1.jpg');  //复制文件到新的路径$disk->move('old/file1.jpg', 'new/file1.jpg');  //移动文件到新的路径$size = $disk->size('file1.jpg');               //取得文件大小$time = $disk->lastModified('file1.jpg');       //取得最近修改时间 (UNIX)$files = $disk->files($directory);              //取得目录下所有文件$files = $disk->allFiles($directory);               //这个没实现。。。$directories = $disk->directories($directory);      //这个也没实现。。。$directories = $disk->allDirectories($directory);   //这个也没实现。。。$disk->makeDirectory($directory);               //这个其实没有任何作用$disk->deleteDirectory($directory);             //删除目录,包括目录下所有子文件子目录$disk->uploadToken('file.jpg');                     //获取上传Token$disk->downloadUrl('file.jpg');                     //获取下载地址$disk->downloadUrl('file.jpg', 'https');            //获取HTTPS下载地址$disk->privateDownloadUrl('file.jpg');              //获取私有bucket下载地址$disk->privateDownloadUrl('file.jpg', 'https');     //获取私有bucket的HTTPS下载地址$disk->imageInfo('file.jpg');                       //获取图片信息$disk->imageExif('file.jpg');                       //获取图片EXIF信息$disk->imagePreviewUrl('file.jpg','imageView2/0/w/100/h/200');                          //获取图片预览URL$disk->persistentFop('file.flv','avthumb/m3u8/segtime/40/vcodec/libx264/s/320x240');    //执行持久化数据处理$disk->persistentFop('file.flv','fop','队列名');    //使用私有队列执行持久化数据处理$disk->persistentStatus($persistent_fop_id);        //查看持久化数据处理的状态。

3、相关参考

本扩展包GitHub地址为 https://github.com/zgldh/qiniu-laravel-storage ,基于 https://github.com/qiniu/php-sdk 开发,更多详情请参考七牛官方PHP SDK使用指南: http://developer.qiniu.com/code/v7/sdk/php.html

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download

Atom editor mac version download

The most popular open source editor