图片上传

<?php
/**
 * User: xmz
 * Date: 2020-06-18
 * Time: 00:15
 */

namespace appadmincontroller;


use appcommonlibUpload;

class Image extends Base
{
    /**
     * 上传文件到本地
     */
    public function upload0()
    {
        $file = $this->request->file('file');

        $info = $file->validate(['size' => 5 * 1024 * 1024, 'ext' => 'gif,jpg,jpeg,bmp,png'])->move('upload');
        if( $info ) {
            return $this->result(
                "/" . $info->getPathname(), 1, "上传成功", "json"
            );
        }

        return $this->result('', 0, "上传失败", "json");
    }

    /**
     * 上传文件到七牛云
     */
    public function  upload(){

        try{
            $image =  Upload::Image();
        }catch (Exception $e){
            return $this->result('', 0, "上传失败", "json");
        }
        if($image){
            return $this->result(config('qiniu.image_url')."/".$image, 1, "ok", "json");
        }
        return $this->result('', 0, "上传失败", "json");


    }
}
<?php
/**
 * User: xmz
 * Date: 2020-06-27
 * Time: 00:08
 */

namespace appcommonlib;

use QiniuAuth;
use QiniuStorageUploadManager;

class Upload
{
    /**
     * 上传到七牛
     */
    public static function Image()
    {
        if( empty($_FILES) || empty($_FILES['file']['tmp_name']) ) {
            exception('上传失败');
        }
        $file = $_FILES['file']['tmp_name'];
        $pathinfo = pathinfo($_FILES['file']['name']);
        $ext = $pathinfo['extension'];
        $auth = new Auth(config('qiniu.ak'),config('qiniu.sk'));
        $bucket = config('qiniu.bucket');
        $token = $auth->uploadToken($bucket);
        $upload = new UploadManager();
        $key = date('Y')."/".date('m')."/".date('d').'/'.substr(md5($file), 0, 5) . date('YmdHis') . rand(0, 9999) . '.' . $ext;
        try{
         list($ret,$err)  = $upload->putFile($token,$key,$file);
          if($err !== null){
              return null;
          }
          return $key;
          //ok
//            rray(2) {
//            [0] =&gt; array(2) {
//                ["hash"] =&gt; string(28) "FmrLAk67ktfED_xdMyw-yo4mU3G2"
//                ["key"] =&gt; string(38) "2020/06/27/63504202006270030495128.png"
//  }
//  [1] =&gt; NULL
//}
           // list($ret,$err)
        }catch (Exception $e){
            exception($e->getMessage());
        }

    }
}
  
 

  

原文地址:https://www.cnblogs.com/aln0825/p/13196990.html