PHP异步上传处理

该PHP代码实现了一个异步文件上传控制器,支持图片和docx文档上传。通过ThinkPHP框架,文件首先被保存到服务器本地指定路径,然后根据文件类型移动到对应的文件夹。使用OSSClient进行阿里云对象存储服务的文件上传,确保文件的安全存储。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<?php
namespace Api\Controller;

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods' 'GET, POST'");

use Think\Controller;

class ImgBankUploadController extends Controller
{

    public $uploadRoute;
    public $uploadDocx;

    public function __construct()
    {
        parent::__construct();
        //图片文件路径
        $this->uploadRoute = "/Public/Uploads/Industry/" . date("Y") . '/' . date("m") . '/' . date("d") . '/';
        //文档上传路径
        $this->uploadDocx = "/Public/Uploads/Authority/" . date("Y") . '/' . date("m") . '/' . date("d") . '/';
    }

    public function index()
    {
        foreach ($_FILES as $key => $v) {
            //文件类型
            $type = end(explode('.', $v['name']));
        }

        $time = time();
        $getRandomString = $this->getRandomString(8);
        $upload = new \Think\Upload();                           // 实例化上传类
        $upload->maxSize = 471859;                              // 设置附件上传大小
        $upload->saveName = array('uniqid', $time . $getRandomString);
        // $upload->exts = array('jpg', 'gif', 'png', 'jpeg','docx');// 设置附件上传类型
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
      
      $upload->saveExt = 'jpg';
      
        $this->getFile($type);                                     //创建文件夹 
        if ($type == 'docx') {
            $upload->rootPath = $_SERVER['DOCUMENT_ROOT'] . $this->uploadDocx; // 设置附件上传根目录
        } else {
            $upload->rootPath = $_SERVER['DOCUMENT_ROOT'] . $this->uploadRoute; // 设置附件上传根目录
        }
        $upload->savePath = ''; // 设置附件上传(子)目录

        // 上传文件
        $info = $upload->upload();
        if (!$info) {// 上传错误提示错误信息
            echo json_encode(['code' => 2, 'msg' => $upload->getError(), 'url' => $url2]);
            exit;

        } else {// 上传成功
            foreach ($info as $file) {
                $url = $file['savepath'] . $file['savename'];
                if ($type == 'docx') {
                    $url2 = $this->uploadDocx . $url; // 设置附件上传根目录
                } else {
                    $url2 = $this->uploadRoute . $url; // 设置附件上传根目录
                }
            }
         
      $Oss_file ='.'.$url2;
      $OssClient = new \Service\OssClient();
      $Oss_file_Name = $OssClient->uploadFile($Oss_file,'','bank',$type=2);
      if($Oss_file_Name['code']==1000){
          $this->ajaxReturn(['code' => 1, 'msg' => '上传成功', 'url' => $Oss_file_Name['url']]);
      }else{
         $this->ajaxReturn(['code' => 0, 'msg' => '上传失败', 'url' => ""]);
      }     
       // echo json_encode(['code' => 1, 'msg' => '上传成功', 'url' => $url2]);
       // exit;
       }
    }


    //创建文件夹
    public function getFile($type)
    {
        if ($type == 'docx') {
            $dest_dir = dirname(dirname(dirname(dirname(__FILE__)))) . $this->uploadDocx;
            if (!is_dir($dest_dir) || !is_writeable($dest_dir)) {
                $dest_dir1 = dirname(dirname(dirname(dirname(__FILE__)))) . '/Public/Uploads/Authority/' . date("Y");
                $dest_dir2 = dirname(dirname(dirname(dirname(__FILE__)))) . '/Public/Uploads/Authority/' . date("Y") . '/' . date("m");
                $dest_dir3 = dirname(dirname(dirname(dirname(__FILE__)))) . $this->uploadDocx;
                mkdir($dest_dir1, 0777, true);
                chmod($dest_dir1, 0777);
                mkdir($dest_dir2, 0777, true);
                chmod($dest_dir2, 0777);
                mkdir($dest_dir3, 0777, true);
                chmod($dest_dir3, 0777);
            }
        } else {
            $dest_dir = dirname(dirname(dirname(dirname(__FILE__)))) . $this->uploadRoute;
            if (!is_dir($dest_dir) || !is_writeable($dest_dir)) {
                $dest_dir1 = dirname(dirname(dirname(dirname(__FILE__)))) . '/Public/Uploads/Industry/' . date("Y");
                $dest_dir2 = dirname(dirname(dirname(dirname(__FILE__)))) . '/Public/Uploads/Industry/' . date("Y") . '/' . date("m");
                $dest_dir3 = dirname(dirname(dirname(dirname(__FILE__)))) . $this->uploadRoute;
                mkdir($dest_dir1, 0777, true);
                chmod($dest_dir1, 0777);
                mkdir($dest_dir2, 0777, true);
                chmod($dest_dir2, 0777);
                mkdir($dest_dir3, 0777, true);
                chmod($dest_dir3, 0777);
            }
        }
        return true;
    }


    public function phoneImg()
    {
        $base64_string = $_POST['base64_string'];
        $savename = time() . mt_rand(5, 10) . uniqid() . $this->getRandomString(8) . '.jpg';//localResizeIMG压缩后的图片都是jpeg格式
        $dest_dir = $_SERVER['DOCUMENT_ROOT'] . "/Public/Uploads/Phone/" . date("Y") . '/' . date("m") . '/' . date("d");
        if (!is_dir($dest_dir) || !is_writeable($dest_dir)) {
            $dest_dir1 = $_SERVER['DOCUMENT_ROOT'] . '/Public/Uploads/Phone/' . date("Y");
            $dest_dir2 = $_SERVER['DOCUMENT_ROOT'] . '/Public/Uploads/Phone/' . date("Y") . '/' . date("m");
            $dest_dir3 = $_SERVER['DOCUMENT_ROOT'] . '/Public/Uploads/Phone/' . date("Y") . '/' . date("m") . '/' . date("d");
            mkdir($dest_dir1, 0777, true);
            chmod($dest_dir1, 0777);
            mkdir($dest_dir2, 0777, true);
            chmod($dest_dir2, 0777);
            mkdir($dest_dir3, 0777, true);
            chmod($dest_dir3, 0777);
        }
        $savepath = $_SERVER['DOCUMENT_ROOT'] . "/Public/Uploads/Phone/" . date("Y") . '/' . date("m") . '/' . date("d").'/'.$savename;  //上传的路径
        $image = self::base64_to_img($base64_string, $savepath);
        $url_path = '/Public/Uploads/Phone/'.date("Y").'/'.date("m").'/'.date("d").'/' . $savename;
      
      //$file, $newname, $path = 'bank',$type=1
       $Oss_file ='.'.$url_path;
      $OssClient = new \Service\OssClient();
      $Oss_file_Name = $OssClient->uploadFile($Oss_file,'','bank',$type=2);
      if($Oss_file_Name['code']==1000){
          $this->ajaxReturn(['code' => 1, 'msg' => '上传成功', 'url' => $Oss_file_Name['url']]);
      }else{
         $this->ajaxReturn(['code' => 0, 'msg' => '上传失败', 'url' => ""]);
      }    
    }



   /*富友上传图片fuiou
   */
   public function fyUpload()
     {
       $base64_string = $_POST['base64_string'];
      $img_name = $_POST['img_name'];
      $merchant_num =$_POST['merchant_num'];
      if(!$img_name || !$merchant_num){
         echo json_encode(['code' => 2, 'msg' => '文件名称或门店编号不能为空']);
            exit;
      }else{//创建文件
       $dest_dir = $_SERVER['DOCUMENT_ROOT']."/Public/Uploads/Fuyou/".$merchant_num;
         if (!is_dir($dest_dir) || !is_writeable($dest_dir)) {
            mkdir($dest_dir, 0777, true);
            chmod($dest_dir, 0777);
         } 
      $savename = $img_name.'.jpg';
      $savepath = $dest_dir.'/'.$savename;  //上传的路径
      rename($image,$image);
        $image = self::base64_to_img($base64_string, $savepath);
      $url = "/Public/Uploads/Fuyou/".$merchant_num.'/'.$savename;
      $Oss_file ='.'.$url;
      $OssClient = new \Service\OssClient();
      $Oss_file_Name = $OssClient->uploadFile($Oss_file,'','bank',$type=2);
      if($Oss_file_Name['code']==1000){
          $this->ajaxReturn(['code' => 1, 'msg' => '上传成功', 'url' => $Oss_file_Name['url']]);
      }else{
         $this->ajaxReturn(['code' => 0, 'msg' => '上传失败', 'url' => ""]);
      }     
   // $this->ajaxReturn(['code' => 1, 'msg' => '上传成功', 'url' => $url]);  exit;
      }
    }
   
   
   
   
   
/* public function fyUpload()
     {
        foreach ($_FILES as $key => $v) {
            $type = end(explode('.', $v['name']));  //文件类型
        }
      
      $img_name = $_POST['img_name'];
      $merchant_num =$_POST['merchant_num'];
      $upload_path = "/Public/Uploads/Fuyou/".$merchant_num."/";
      if(!$img_name || !$merchant_num){
         echo json_encode(['code' => 2, 'msg' => '文件名称或门店编号不能为空']);
            exit;
      }
      
        $upload = new \Think\Upload();                           // 实例化上传类
        $upload->maxSize = 471859;                              // 设置附件上传大小
      $upload->saveName = $img_name; 
      $upload->replace = true; 
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
      $upload->saveExt = 'jpg';
      
      //判断文件是否存在创建文件
      $dest_dir = $_SERVER['DOCUMENT_ROOT'].$upload_path;
      if (!is_dir($dest_dir) || !is_writeable($dest_dir)) {
         $dest_dir1 = $_SERVER['DOCUMENT_ROOT'].$upload_path;
         mkdir($dest_dir1, 0777, true);
         chmod($dest_dir1, 0777);
      }
        $upload->rootPath =  $_SERVER['DOCUMENT_ROOT'].$upload_path; // 设置附件上传根目录
        $upload->savePath = ''; // 设置附件上传(子)目录
        // 上传文件
        $info = $upload->upload();
        if (!$info) {// 上传错误提示错误信息
            echo json_encode(['code' => 2, 'msg' => $upload->getError(), 'url' => $url2]);
            exit;

        } else {// 上传成功
            foreach ($info as $file) {
                $url = $file['savepath'] . $file['savename'];
                $url2 =  $upload_path. $url; // 设置附件上传根目录
            }
            echo json_encode(['code' => 1, 'msg' => '上传成功', 'url' => $url2]);
            exit;
        }
     }*/


    /*
 * 获取64位文件
 * */
    public function base64_to_img($base64_string, $output_file)
    {
        $ifp = fopen($output_file, "wb");
        fwrite($ifp, base64_decode($base64_string));
        fclose($ifp);
        return ($output_file);
    }


    //随机数
    public function getRandomString($len, $chars = null)
    {
        if (is_null($chars)) {
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        }
        mt_srand(10000000 * (double)microtime());
        for ($i = 0, $str = '', $lc = strlen($chars) - 1; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $lc)];
        }
        return $str;
    }
   
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值