TP6上传图片到OSS(记录贴)

1,先安装,我使用composer安装
在项目的根目录运行composer require aliyuncs/oss-sdk-php

2,安装成功以后vendor目录下可以看到如图:

3,上传图片代码如下:

<?php
namespace app\controller;

use app\BaseController;

use OSS\OssClient;
use OSS\Core\OssException;

class Index extends BaseController
{
     /*
    * 图片上传,将图片上传至阿里云oss
    * */
    public function upload(){
        $files = $_FILES['file'];
        $name = $files['name'];
        $format = strrchr($name, '.');//截取文件后缀名如 (.jpg)
        // 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录RAM控制台创建RAM账号。
        $accessKeyId = "<yourAccessKeyId>";
        $accessKeySecret = "<yourAccessKeySecret>";
        // Endpoint以杭州为例,其它Region请按实际情况填写。
        $endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
        // 设置存储空间名称。
        $bucket= "<yourBucketName>";
        // 设置文件名称。
        //这里是由sha1加密生成文件名 之后连接上文件后缀,生成文件规则根据自己喜好,也可以用md5
        //前面video/head/ 这是我的oss目录
        $object = 'video/head/'.sha1(date('YmdHis', time()) . uniqid()) . $format;;
        // <yourLocalFile>由本地文件路径加文件名包括后缀组成,例如/users/local/myfile.txt。
        $filePath = $files['tmp_name'];

        try{
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

            $result = $ossClient->uploadFile($bucket, $object, $filePath);
            if(!$result){
                return json(['status'=>1,'message'=>'上传失败']);
            }else{
                return json(['status'=>2,'message'=>'上传成功','url'=>$result['info']['url']]);
            }
        } catch(OssException $e) {
            printf(__FUNCTION__ . ": FAILED\n");
            printf($e->getMessage() . "\n");
            return;
        }
        print(__FUNCTION__ . ": OK" . "\n");
    }
}

中途遇到的一些问题

1.没安装或没启用curl拓展,PHP安装curl拓展就好

upload: FAILED
Extension {curl} is not installed or not enabled, please check your php env.

2.上传后地址打开不正确,Bucket权限可能是私有,改成正常读,不然就地址要加权限验证

-------------------------------------------------------------------------------------------------------------------------------

另一种方式:(会先传到本地服务器文件夹再传到oss);

1.公共方法

<?php

use OSS\OssClient;
use OSS\Core\OssException;
use think\facade\Config;
//阿里云OSS
if (!function_exists('aliyun')) {
    /**
     * @param $savePath 文件名称
     * @param string $category oss存储目录
     * @param bool $isunlink
     * @param string $bucket 存储空间名称
     * @return string
     * @throws OssException
     * @throws \OSS\Http\RequestCore_Exception
     */
    function aliyun($savePath,$category='',$isunlink=false,$bucket=""){
        $accessKeyId = Config::get('app.aliyun_oss.accessKeyId');//去阿里云后台获取秘钥
        $accessKeySecret = Config::get('app.aliyun_oss.accessKeySecret');//去阿里云后台获取秘钥
        $endpoint = Config::get('app.aliyun_oss.endpoint');//你的阿里云OSS地址
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        //        判断bucketname是否存在,不存在就去创建
        if( !$ossClient->doesBucketExist($bucket)){
            $ossClient->createBucket($bucket);
        }
        $category=empty($category)?$bucket:$category;

        $savePath = str_replace("\\","/",$savePath);

        $object = $category.'/'.$savePath;//想要保存文件的名称
//        $file = './upload\\'.$savePath;//文件路径,必须是本地的。//发现这个不行,要用绝对路径
        $file = app()->getRootPath() ."public/storage/upload\\".$savePath;//文件路径,必须是本地的。

        try{
            $ossClient->uploadFile($bucket,$object,$file);
            if ($isunlink==true){
                unlink($file);
            }
        }catch (OssException $e){
            $e->getErrorMessage();
        }
        $oss=Config::get('aliyun_oss.url');
        $web = "http://test.oss-cn-hangzhou.aliyuncs.com.aliyuncs.com";//这里是你阿里云oss外网访问的Bucket域名
        return $web.$oss."/".$object;
    }
}

2.在config app中配置阿里云参数

//阿里云配置
    'aliyun_oss' => [
        'accessKeyId'      => '',  //您的Access Key ID
        'accessKeySecret'  => '',  //您的Access Key Secret
        'endpoint'   => 'oss-cn-shanghai.aliyuncs.com',  //阿里云oss 外网地址endpoint
        'bucket'     => '',  //Bucket名称
        'url'           => ''  // 访问的地址 (可不配置)
    ]

3.封装tp6的文件上传方法 并上传oss (也可以放公共文件里)

<?php
 
use think\facade\Filesystem;
 
if (!function_exists('uplodeOss')) {
    function uplodeOss($file){
        //上传到public目录下的storage下的upload目录
        $path = Filesystem::disk('public')->putFile('upload', $file);
//图片路径,Filesystem::getDiskConfig('public','url')功能是获取public目录下的storage,
        $ossPath = substr(strrchr($path, "/"), 1);
//结果是 $picCover = storage/upload/20200825/***.jpg
        $picCover = '/' . str_replace('\\', '/', $path);//图片上传到本地的路径
//上传OSS 并获取阿里云OSS地址
        $image = aliyun($ossPath, '', '', '<yourBucketName>');//第一个参数为图片地址 最后一个为bucket名字 具体参数在上个方法中
        if($image){
            return $image;
        }
    }
}

4.方法中调用

public function upload(){

   $files = request()->file('file');
   $result = uplodeOss($files);

   var_dump($result);
}

不能用 $_FILES,要用request()->file('');

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Spring Boot中将图片上传到OSS(阿里云对象存储),可以使用阿里云提供的Java SDK进行操作。以下是一个简单的实现步骤: 1.添加依赖 在你的pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.10.1</version> </dependency> ``` 2.配置OSS客户端 在你的application.properties文件中添加OSS的配置信息: ```properties aliyun.oss.endpoint=oss-cn-hangzhou.aliyuncs.com aliyun.oss.accessKeyId=yourAccessKeyId aliyun.oss.accessKeySecret=yourAccessKeySecret aliyun.oss.bucketName=yourBucketName ``` 接着,创建一个OSS客户端实例: ```java @ConfigurationProperties(prefix = "aliyun.oss") @Component public class OSSClientConfig { private String endpoint; private String accessKeyId; private String accessKeySecret; private String bucketName; @Bean public OSSClient ossClient() { return new OSSClient(endpoint, accessKeyId, accessKeySecret); } // getters and setters } ``` 3.编写上传代码 在你的Controller中编写上传代码: ```java @RestController @RequestMapping("/upload") public class UploadController { @Autowired private OSSClient ossClient; @PostMapping("/image") public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file) { try { // 获取文件名 String fileName = file.getOriginalFilename(); // 创建一个唯一的文件名 String uniqueFileName = UUID.randomUUID().toString() + "_" + fileName; // 上传文件到OSS ossClient.putObject("yourBucketName", uniqueFileName, file.getInputStream()); // 返回文件的访问URL String fileUrl = "https://yourBucketName.oss-cn-hangzhou.aliyuncs.com/" + uniqueFileName; return ResponseEntity.ok(fileUrl); } catch (IOException e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("上传失败"); } } } ``` 这段代码将上传的文件存储到OSS,并返回文件的访问URL。 以上就是一个简单的Spring Boot上传图片OSS的实现方式。当然,还有很多细节需要注意,比如上传文件的大小限制等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值