其他分享
首页 > 其他分享> > Laravel6 alioss上传csv 并读取远程csv文件

Laravel6 alioss上传csv 并读取远程csv文件

作者:互联网

1.composer安装阿里云oss插件;

composer require johnlui/aliyun-oss:~2.0

2.app/services/OSS.php

<?php

namespace App\Services;

use JohnLui\AliyunOSS;

use Exception;
use DateTime;

class OSS {

  /* 城市名称:
   *  
   *  经典网络下可选:杭州、上海、青岛、北京、张家口、深圳、香港、硅谷、弗吉尼亚、新加坡、悉尼、日本、法兰克福、迪拜
   *  VPC 网络下可选:杭州、上海、青岛、北京、张家口、深圳、硅谷、弗吉尼亚、新加坡、悉尼、日本、法兰克福、迪拜
   */    
  private $city = '青岛';

  // 经典网络 or VPC
  private $networkType = '经典网络';
  
  private $AccessKeyId = '';
  private $AccessKeySecret = '';


  private $ossClient;

  /**
   * 私有初始化 API,非 API,不用关注
   * @param boolean 是否使用内网
   */
  public function __construct($isInternal = false)
  {
    if ($this->networkType == 'VPC' && !$isInternal) {
      throw new Exception("VPC 网络下不提供外网上传、下载等功能");
    }
    $this->ossClient = AliyunOSS::boot(
      $this->city,
      $this->networkType,
      $isInternal,
      $this->AccessKeyId,
      $this->AccessKeySecret
    );
  }


  /**
   * 使用外网上传文件
   * @param  string bucket名称
   * @param  string 上传之后的 OSS object 名称
   * @param  string 上传文件路径
   * @return boolean 上传是否成功
   */
  public static function publicUpload($bucketName, $ossKey, $filePath, $options = [])
  {
    $oss = new OSS();
    $oss->ossClient->setBucket($bucketName);
    return $oss->ossClient->uploadFile($ossKey, $filePath, $options);
  }

  /**
   * 使用阿里云内网上传文件
   * @param  string bucket名称
   * @param  string 上传之后的 OSS object 名称
   * @param  string 上传文件路径
   * @return boolean 上传是否成功
   */
  public static function privateUpload($bucketName, $ossKey, $filePath, $options = [])
  {
    $oss = new OSS(true);
    $oss->ossClient->setBucket($bucketName);
    return $oss->ossClient->uploadFile($ossKey, $filePath, $options);
  }


  /**
   * 使用外网直接上传变量内容
   * @param  string bucket名称
   * @param  string 上传之后的 OSS object 名称
   * @param  string 上传的变量
   * @return boolean 上传是否成功
   */
  public static function publicUploadContent($bucketName, $ossKey, $content, $options = [])
  {
    $oss = new OSS();
    $oss->ossClient->setBucket($bucketName);
    return $oss->ossClient->uploadContent($ossKey, $content, $options);
  }

  /**
   * 使用阿里云内网直接上传变量内容
   * @param  string bucket名称
   * @param  string 上传之后的 OSS object 名称
   * @param  string 上传的变量
   * @return boolean 上传是否成功
   */
  public static function privateUploadContent($bucketName, $ossKey, $content, $options = [])
  {
    $oss = new OSS(true);
    $oss->ossClient->setBucket($bucketName);
    return $oss->ossClient->uploadContent($ossKey, $content, $options);
  }


  /**
   * 使用外网删除文件
   * @param  string bucket名称
   * @param  string 目标 OSS object 名称
   * @return boolean 删除是否成功
   */
  public static function publicDeleteObject($bucketName, $ossKey)
  {
    $oss = new OSS();
    $oss->ossClient->setBucket($bucketName);
    return $oss->ossClient->deleteObject($bucketName, $ossKey);
  }

  /**
   * 使用阿里云内网删除文件
   * @param  string bucket名称
   * @param  string 目标 OSS object 名称
   * @return boolean 删除是否成功
   */
  public static function privateDeleteObject($bucketName, $ossKey)
  {
    $oss = new OSS(true);
    $oss->ossClient->setBucket($bucketName);
    return $oss->ossClient->deleteObject($bucketName, $ossKey);
  }


  /**
   * -------------------------------------------------
   *
   * 
   *  下面不再分公网内网出 API,也不注释了,大家自行体会吧。。。
   *
   * 
   * -------------------------------------------------
   */

  public function copyObject($sourceBuckt, $sourceKey, $destBucket, $destKey)
  {
    $oss = new OSS();
    return $oss->ossClient->copyObject($sourceBuckt, $sourceKey, $destBucket, $destKey);
  }

  public function moveObject($sourceBuckt, $sourceKey, $destBucket, $destKey)
  {
    $oss = new OSS();
    return $oss->ossClient->moveObject($sourceBuckt, $sourceKey, $destBucket, $destKey);
  }

  // 获取公开文件的 URL
  public static function getPublicObjectURL($bucketName, $ossKey)
  {
    $oss = new OSS();
    $oss->ossClient->setBucket($bucketName);
    return $oss->ossClient->getPublicUrl($ossKey);
  }
  // 获取私有文件的URL,并设定过期时间,如 \DateTime('+1 day')
  public static function getPrivateObjectURLWithExpireTime($bucketName, $ossKey, DateTime $expire_time)
  {
    $oss = new OSS();
    $oss->ossClient->setBucket($bucketName);
    return $oss->ossClient->getUrl($ossKey, $expire_time);
  }

  public static function createBucket($bucketName)
  {
    $oss = new OSS();
    return $oss->ossClient->createBucket($bucketName);
  }

  public static function getAllObjectKey($bucketName)
  {
    $oss = new OSS();
    return $oss->ossClient->getAllObjectKey($bucketName);
  }

  public static function getObjectMeta($bucketName, $ossKey)
  {
    $oss = new OSS();
    return $oss->ossClient->getObjectMeta($bucketName, $ossKey);
  }

}

3.在 composer.jsonautoload -> classmap 处增加配置(composer.json在lavarel项目的根目录下):

"autoload": {
    "classmap": [
      "app/services"
    ]
  }

4.运行命令(注意切换到项目根目录):

composer dump-autoload

5.应用(比如在控制器里边应用):

<?php
namespace App\Http\Controllers;
/*....省略其他命名空间的引用*/
use App\Services\OSS;

class TestController extends Controller
{
    public function __construct()
    {
        
        parent::__construct();
    }


    /**
     *
     * csv 读取
     */
    public function opt(Request $request){
        ini_set('memory_limit','1024M');    // 临时设置最大内存占用为3G
        set_time_limit(0);   // 设置脚本最大执行时间 为0 永不过期
        $ex = $_FILES['file'];
        if ($ex['error']) {
            return back()->with('error', '未提交文件。请选择要导入的文件,然后重试');
        }
        try {
            $bucket = "bucket_name";
            $filename = time() . substr($ex['name'], stripos($ex['name'], '.'));
            $alios =  OSS::publicUpload($bucket, $filename, $ex['tmp_name']);
            if(!$alios){
                //错误处理
		exit("err1");
				
            }
            $path =  OSS::getPublicObjectURL($bucket,$filename);
            if(!$path){
               //错误处理
	        exit("err2");
            }
            $data = $this->read_csv($path);
	    print_r($data);
            
    }

	/**
	*读取csv内容
        *代码来源地址:https://www.jb51.net/article/104814.htm
	*
	*/
    function read_csv($cvs) {
        $shuang = false;
        $str = file_get_contents($cvs);
        $str = iconv('gbk', 'utf-8', $str);
        for ($i=0;$i<strlen($str);$i++) {
            if($str{$i}=='"') {
                if($shuang) {
                    if($str{$i+1}=='"') {
                        $str{$i} = '*';
                        $str{$i+1} = '*';
                    } else {
                        $shuang = false;
                    }
                } else {
                    $shuang = true;
                }
            }
            if($str{$i}==',') {
                if($shuang) {
                } else {
                    $str{$i} = '|';
                }
            }
            if($str{$i}=="\n") {
                if($shuang) {
                    $str{$i} = '^';
                } else {
                }
            }
        }
        $str = str_replace(array('"','*'),array('','"'),$str);
        $a1 = explode("\n",$str);
        $array = array();
        foreach($a1 as $k=>$value) {
            if($value) {
                $value = str_replace("^","\n",$value);
                $array[$k] = explode("|",$value);
            }
        }
        return $array;
    }
}

标签:ossKey,alioss,return,oss,Laravel6,ossClient,bucketName,csv,OSS
来源: https://blog.csdn.net/dreamLeadToword/article/details/118755107