通过本地文件上传
@param $filePath
@param null $key
@param string $bucket
@throws \Exception
4664
public function uploadFile($filePath, $key = null, $bucket = '')
    {
        if (!file_exists($filePath)) {
            throw new \Exception("上传的文件不存在",400);
        }
        $bucket = $bucket ? $bucket : $this->bucket;

        $uploadToken = $this->uploadToken(array('scope' => $bucket));
        $data = [];
        if (class_exists('\CURLFile')) {
            $data['file'] = new \CURLFile($filePath);
        } else {
            $data['file'] = '@' . $filePath;
        }
        $data['token'] = $uploadToken;
        if ($key) {
            $data['key'] = $key;
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->up_host);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $result = curl_exec($ch);
        $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        $result = $this->response($result);
        if ($status == 200) {
            return $result;
        } else {
            throw new \Exception($result['error'],$status);
        }
    }
306557
public Response put(String filePath, String key, String token) throws QiniuException {
        return put(filePath, key, token, null, null, false);
    }
839449
private function uploadFile($bucket, $dstPath, $filecontent, $mime_type, $bizAttr = null, $insertOnly = null)
    {
        $dstPath = self::cosUrlEncode($dstPath);

        $expired    = time() + self::EXPIRED_SECONDS;
        $url        = self::generateResUrl($bucket, $dstPath);
        $signature  = $this->createReusableSignature($expired, $bucket);
        $fileSha    = sha1($filecontent);

        $data = array(
            'op'        => 'upload',
            'sha'       => $fileSha,
            'biz_attr'  => (isset($bizAttr) ? $bizAttr : ''),
        );

        $data['filecontent'] = $filecontent;

        if (isset($insertOnly) && strlen($insertOnly) > 0) {
            $data['insertOnly'] = (($insertOnly == 0 || $insertOnly == '0' ) ? 0 : 1);
        }

        // 设置文件的 mime 类型
        $data['custom_headers']['Content-Type'] = $mime_type;

        $req = [
            'url'       => $url,
            'method'    => 'post',
            'timeout'   => self::$timeout,
            'data'      => $data,
            'header'    => [
                'Authorization: ' . $signature,
            ],
        ];

        return self::sendRequest($req);
    }
802292
private function getFilePath($filePath = null)
    {
        $filePath = $filePath ?? $this->filePath ?? null;

        if (null === $filePath) {
            throw NoFilePathGivenException::import();
        }

        return $filePath;
    }
1155298
public function changeMime($bucket, $key, $mime)
    {
        $resource = \Qiniu\entry($bucket, $key);
        $encode_mime = \Qiniu\base64_urlSafeEncode($mime);
        $path = '/chgm/' . $resource . '/mime/' . $encode_mime;
        list(, $error) = $this->rsPost($path);
        return $error;
    }
1188756
protected function createReusableSignature($expiration, $bucket, $filepath = null)
    {
        if ( empty($filepath)) {
            return $this->createSignature($expiration, $bucket, null);
        } else {
            if (preg_match('/^\//', $filepath) == 0) {
                $filepath = '/' . $filepath;
            }

            return $this->createSignature($expiration, $bucket, $filepath);
        }
    }
874326
public function create_directory($contextid, $component, $filearea, $itemid, $filepath, $userid = null) {
        global $DB;

        // validate all parameters, we do not want any rubbish stored in database, right?
        if (!is_number($contextid) or $contextid < 1) {
            throw new file_exception('storedfileproblem', 'Invalid contextid');
        }

        $component = clean_param($component, PARAM_COMPONENT);
        if (empty($component)) {
            throw new file_exception('storedfileproblem', 'Invalid component');
        }

        $filearea = clean_param($filearea, PARAM_AREA);
        if (empty($filearea)) {
            throw new file_exception('storedfileproblem', 'Invalid filearea');
        }

        if (!is_number($itemid) or $itemid < 0) {
            throw new file_exception('storedfileproblem', 'Invalid itemid');
        }

        $filepath = clean_param($filepath, PARAM_PATH);
        if (strpos($filepath, '/') !== 0 or strrpos($filepath, '/') !== strlen($filepath)-1) {
            // path must start and end with '/'
            throw new file_exception('storedfileproblem', 'Invalid file path');
        }

        $pathnamehash = $this->get_pathname_hash($contextid, $component, $filearea, $itemid, $filepath, '.');

        if ($dir_info = $this->get_file_by_hash($pathnamehash)) {
            return $dir_info;
        }

        static $contenthash = null;
        if (!$contenthash) {
            $this->add_string_to_pool('');
            $contenthash = self::hash_from_string('');
        }

        $now = time();

        $dir_record = new stdClass();
        $dir_record->contextid = $contextid;
        $dir_record->component = $component;
        $dir_record->filearea  = $filearea;
        $dir_record->itemid    = $itemid;
        $dir_record->filepath  = $filepath;
        $dir_record->filename  = '.';
        $dir_record->contenthash  = $contenthash;
        $dir_record->filesize  = 0;

        $dir_record->timecreated  = $now;
        $dir_record->timemodified = $now;
        $dir_record->mimetype     = null;
        $dir_record->userid       = $userid;

        $dir_record->pathnamehash = $pathnamehash;

        $DB->insert_record('files', $dir_record);
        $dir_info = $this->get_file_by_hash($pathnamehash);

        if ($filepath !== '/') {
            //recurse to parent dirs
            $filepath = trim($filepath, '/');
            $filepath = explode('/', $filepath);
            array_pop($filepath);
            $filepath = implode('/', $filepath);
            $filepath = ($filepath === '') ? '/' : "/$filepath/";
            $this->create_directory($contextid, $component, $filearea, $itemid, $filepath, $userid);
        }

        return $dir_info;
    }
300006
public function appendFile($bucket, $object, $file, $position, $options = NULL)
    {
        $this->precheckCommon($bucket, $object, $options);

        OssUtil::throwOssExceptionWithMessageIfEmpty($file, "file path is invalid");
        $file = OssUtil::encodePath($file);
        if (!file_exists($file)) {
            throw new OssException($file . " file does not exist");
        }
        $options[self::OSS_FILE_UPLOAD] = $file;
        $file_size = filesize($options[self::OSS_FILE_UPLOAD]);
        $is_check_md5 = $this->isCheckMD5($options);
        if ($is_check_md5) {
            $content_md5 = base64_encode(md5_file($options[self::OSS_FILE_UPLOAD], true));
            $options[self::OSS_CONTENT_MD5] = $content_md5;
        }
        if (!isset($options[self::OSS_CONTENT_TYPE])) {
            $options[self::OSS_CONTENT_TYPE] = $this->getMimeType($object, $file);
        }

        $options[self::OSS_METHOD] = self::OSS_HTTP_POST;
        $options[self::OSS_BUCKET] = $bucket;
        $options[self::OSS_OBJECT] = $object;
        $options[self::OSS_CONTENT_LENGTH] = $file_size;
        $options[self::OSS_SUB_RESOURCE] = 'append';
        $options[self::OSS_POSITION] = strval($position);

        $response = $this->auth($options);
        $result = new AppendResult($response);
        return $result->getData();
    }
1138118
public static function loadEncryptionKeyPair(string $filePath): EncryptionKeyPair
    {
        if (!\is_readable($filePath)) {
            throw new CannotPerformOperation(
                'Cannot read keyfile: '. $filePath
            );
        }
        return new EncryptionKeyPair(
            new EncryptionSecretKey(
                self::loadKeyFile($filePath)
            )
        );
    }
886575
public function locate($filePath)
    {
        $file = $filePath;
        if (!is_file($filePath))
        {
            throw new FileException(sprintf('Invalid file! File "%s" does not exist.',
                                            $filePath));
        }

        if (!is_readable($filePath))
        {
            throw new FileException(sprintf('Invalid file! File "%s" is not readable.',
                                            $filePath));
        }

        $pathInfo = pathinfo($filePath);
        if (!isset($pathInfo['extension'])
            || !in_array($pathInfo['extension'], $this->supportedExtensions)
        )
        {
            throw new FileException(sprintf('Invalid file extension! Supported file extensions: %s',
                implode(', ', $this->supportedExtensions)));
        }

        return realpath($file);
    }
544209
public function saveContentToFile($filePath, $content)
	{
		return $this->s3Client->putObject([
			'Bucket' => $this->getBucket(),
			'Key' => $filePath,
			'Body' => $content
		]);
	}
1199991
protected function init($filepath)
    {
        $this->file = new \SplFileObject($filepath);

        if (!$this->file->isFile()) {
            throw new \LogicException('This is not a file', 1);
        }

        if (!$this->file->isReadable()) {
            throw new \Exception('This file is not readable', 1);
        }

        if (!$this->file->isWritable()) {
            //throw new \Exception("This file is not writable", 1);
        }

        $this->filepath = $this->file->getPathName();
    }
1062096
public function uploadFile($key, $filePath, $deleteAfterUpload = true)
    {
        if (is_dir($filePath) && false === is_dir($this->mediaDirectory)) {
            throw new BadFileException();
        }
        $targetFile = $this->computePath($key);
        $this->fileSystem->copy($filePath, $targetFile);

        if ($deleteAfterUpload) {
            $this->fileSystem->remove($filePath);
        }
    }
244976
public function setFile($filePath = '.gitignore')
    {
        $this->fileContent = array();
        $this->afterLine = null;
        $this->filePath = $filePath;
        $this->checkPermissions();
        $this->parse();
    }
753188
public function getFilePath( string$filePath, string$path=null ):string
	{
		if( !isset($this->basePath) )
			{ throw new \Exception('BasePath musbe set.'); }

		if( !strlen($filePath) )
			{ throw new \Exception('FilePath cannot be empty.'); }

		if( '/'===$filePath{0} ){
			if( is_null($path) )
				{ return $filePath; }
			else
				{ return $this->basePath.$filePath; }
		}else{
			if( !strlen($path) )
				{ return $this->basePath.'/'.$filePath; }
			elseif( '/'===substr($path,-1) )
				{ return $path.$filePath; }
			else
				{ return $path.'/'.$filePath; }
		}

	}
18654
public static function create($filePath)
    {
        if (!file_exists($filePath)) {
            throw new Exception(["{$filePath} has not been found"]);
        }

        $file = fopen($filePath, 'r');

        $photo = json_decode(
            self::post(
                "photos",
                [
                    'multipart' => [['name' => 'photo', 'contents' => $file]],
                    'headers' => ['Content-Length' => filesize($filePath)]
                ]
            )->getBody(),
            true
        );

        return new self($photo);
    }
1208476
public function uploadByUrl($url, $key = null, $bucket = '')
    {
        $filePath = tempnam(sys_get_temp_dir(), 'QN');
        copy($url, $filePath);
        $result = $this->uploadFile($filePath, $key, $bucket);
        unlink($filePath);
        return $result;
    }