Upload file to server.

@param int $totalBytes

@throws ConnectionException

@return int
773744
public function upload(int $totalBytes) : int
    {
        if ($this->offset === $totalBytes) {
            return $this->offset;
        }

        $input  = $this->open($this->getInputStream(), self::READ_BINARY);
        $output = $this->open($this->getFilePath(), self::APPEND_BINARY);
        $key    = $this->getKey();

        try {
            $this->seek($output, $this->offset);

            while ( ! feof($input)) {
                if (CONNECTION_NORMAL !== connection_status()) {
                    throw new ConnectionException('Connection aborted by user.');
                }

                $data  = $this->read($input, self::CHUNK_SIZE);
                $bytes = $this->write($output, $data, self::CHUNK_SIZE);

                $this->offset += $bytes;

                $this->cache->set($key, ['offset' => $this->offset]);

                if ($this->offset > $totalBytes) {
                    throw new OutOfRangeException('The uploaded file is corrupt.');
                }

                if ($this->offset === $totalBytes) {
                    break;
                }
            }
        } finally {
            $this->close($input);
            $this->close($output);
        }

        return $this->offset;
    }
1075221
public function upload($filename, $destination)
    {
        if (isset($this[$filename])) {
            $file = $this[$filename];
            if (is_uploaded_file($file[static::TMP_NAME])) {
                try {
                    return move_uploaded_file($file[static::TMP_NAME], $destination);
                } catch (\Exception $e) {
                    var_dump($e->getMessage());
                    exit();
                }
            }
        }
        return false;
    }
720034
private function addFile(array &$files, string $fieldName, string $filename, string $tmpPath, string $mimeType, bool $err): void
    {
        $data = [
            'type' => $mimeType ?: 'application/octet-stream',
            'name' => $filename,
            'tmp_name' => $tmpPath,
            'error' => $err ? UPLOAD_ERR_CANT_WRITE : UPLOAD_ERR_OK,
            'size' => filesize($tmpPath),
        ];

        $parts = preg_split('|(\[[^\]]*\])|', $fieldName, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
        $count = count($parts);
        if (1 === $count) {
            $files[$fieldName] = $data;
        } else {
            $current = &$files;
            foreach ($parts as $i => $part) {
                if ($part === '[]') {
                    $current[] = $data;
                    continue;
                }

                $trimmedMatch = trim($part, '[]');
                if ($i === $count -1) {
                    $current[$trimmedMatch] = $data;
                } else {
                    $current = &$current[$trimmedMatch];
                }
            }
        }
    }
556761
public function write(string $data): int
	{
		$totalBytesWritten = 0;

		$bytesLeft = strlen($data);

		do
		{
			$totalBytesWritten += $bytesWritten = fwrite($this->connection, $data);

			if($bytesWritten === false || $bytesWritten === 0)
			{
				throw new RedisException('Failed to write data to the server.');
			}

			$bytesLeft -= $bytesWritten;

			$data = substr($data, $bytesWritten);
		}
		while($bytesLeft > 0);

		return $totalBytesWritten;
	}
1235827
def _upload_file_bytes(self, conn, http_conn, fp, file_length,
                           total_bytes_uploaded, cb, num_cb):
        
        buf = fp.read(self.BUFFER_SIZE)
        if cb:
            if num_cb > 2:
                cb_count = file_length / self.BUFFER_SIZE / (num_cb-2)
            elif num_cb < 0:
                cb_count = -1
            else:
                cb_count = 0
            i = 0
            cb(total_bytes_uploaded, file_length)

        # Build resumable upload headers for the transfer. Don't send a
        # Content-Range header if the file is 0 bytes long, because the
        # resumable upload protocol uses an *inclusive* end-range (so, sending
        # 'bytes 0-0/1' would actually mean you're sending a 1-byte file).
        put_headers = {}
        if file_length:
            range_header = self._build_content_range_header(
                '%d-%d' % (total_bytes_uploaded, file_length - 1),
                file_length)
            put_headers['Content-Range'] = range_header
        # Set Content-Length to the total bytes we'll send with this PUT.
        put_headers['Content-Length'] = str(file_length - total_bytes_uploaded)
        http_request = AWSAuthConnection.build_base_http_request(
            conn, 'PUT', path=self.tracker_uri_path, auth_path=None,
            headers=put_headers, host=self.tracker_uri_host)
        http_conn.putrequest('PUT', http_request.path)
        for k in put_headers:
            http_conn.putheader(k, put_headers[k])
        http_conn.endheaders()

        # Turn off debug on http connection so upload content isn't included
        # in debug stream.
        http_conn.set_debuglevel(0)
        while buf:
            http_conn.send(buf)
            total_bytes_uploaded += len(buf)
            if cb:
                i += 1
                if i == cb_count or cb_count == -1:
                    cb(total_bytes_uploaded, file_length)
                    i = 0
            buf = fp.read(self.BUFFER_SIZE)
        if cb:
            cb(total_bytes_uploaded, file_length)
        if total_bytes_uploaded != file_length:
            # Abort (and delete the tracker file) so if the user retries
            # they'll start a new resumable upload rather than potentially
            # attempting to pick back up later where we left off.
            raise ResumableUploadException(
                'File changed during upload: EOF at %d bytes of %d byte file.' %
                (total_bytes_uploaded, file_length),
                ResumableTransferDisposition.ABORT)
        resp = http_conn.getresponse()
        body = resp.read()
        # Restore http connection debug level.
        http_conn.set_debuglevel(conn.debug)

        if resp.status == 200:
            return resp.getheader('etag')  # Success
        # Retry timeout (408) and status 500 and 503 errors after a delay.
        elif resp.status in [408, 500, 503]:
            disposition = ResumableTransferDisposition.WAIT_BEFORE_RETRY
        else:
            # Catch all for any other error codes.
            disposition = ResumableTransferDisposition.ABORT
        raise ResumableUploadException('Got response code %d while attempting '
                                       'upload (%s)' %
                                       (resp.status, resp.reason), disposition)
1362478
public function upload()
    {
        //as upload may be called multiple times, we remove the session lock as soon as possible
        try{
            session_write_close();
            if ($this->hasRequestParameter('uri')) {
                $itemUri = $this->getRequestParameter('uri');
                $item = $this->getResource($itemUri);
            }

            if ($this->hasRequestParameter('lang')) {
                $itemLang = $this->getRequestParameter('lang');
            }

            if (!$this->hasRequestParameter('path')) {
                throw new common_exception_MissingParameter('path', __METHOD__);
            }

            if (!$this->hasRequestParameter('filters')) {
                throw new common_exception_MissingParameter('filters', __METHOD__);
            }
            $filters = $this->getRequestParameter('filters');

            $resolver = new ItemMediaResolver($item, $itemLang);
            $asset = $resolver->resolve($this->getRequestParameter('relPath'));

            $file = tao_helpers_Http::getUploadedFile('content');
            $fileTmpName = $file['tmp_name'].'_'.$file['name'];

            if (!tao_helpers_File::copy($file['tmp_name'], $fileTmpName)) {
                throw new common_exception_Error('impossible to copy '.$file['tmp_name'].' to '.$fileTmpName);
            }

            $mime = \tao_helpers_File::getMimeType($fileTmpName);
            if (is_string($filters)) {
                // the mime type is part of the $filters
                $filters = explode(',', $filters);
                if ((in_array($mime, $filters))) {
                    $filedata = $asset->getMediaSource()->add($fileTmpName, $file['name'],
                        $asset->getMediaIdentifier());
                } else {
                    throw new FileUploadException(__('The file you tried to upload is not valid'));
                }
            } else {
                $valid = false;
                // OR the extension is part of the filter and it correspond to the mime type
                foreach ($filters as $filter) {
                    if ($filter['mime'] === $mime &&
                        (!isset($filter['extension']) || $filter['extension'] === \tao_helpers_File::getFileExtention($fileTmpName))
                    ) {
                        $valid = true;
                    }
                }
                if ($valid) {
                    $filedata = $asset->getMediaSource()->add($fileTmpName, $file['name'],
                        $asset->getMediaIdentifier());
                } else {
                    throw new FileUploadException(__('The file you tried to upload is not valid'));
                }
            }

            $this->returnJson($filedata);
            return;
        }
        catch(PermissionException $e){
            $message = $e->getMessage();
        }
        catch(FileUploadException $e){
            $message = $e->getMessage();
        }
        catch(common_Exception $e){
            $this->logWarning($e->getMessage());
            $message = _('Unable to upload file');
        }
        $this->returnJson(array('error' => $message));

    }
1232995
public function write(string $bytes): int
    {
        if (null === $this->handle) {
            throw new \LogicException('Can not write to closed output stream.');
        }

        $length = @fwrite($this->handle, $bytes);
        if (false === $length) {
            throw new StreamException(
                    'Can not write to output stream:'
                    . lastErrorMessage('unknown error')
            );
        }

        return $length;
    }
487028
public function write(string $bytes): int
    {
        if ($this->isFileCreationDelayed()) {
            $this->setHandle($this->openFile($this->file, $this->mode));
        }

        return parent::write($bytes);
    }
544296
public function write(string $bytes): int
    {
        $isAcceptable = $this->predicate;
        if ($isAcceptable($bytes)) {
            return $this->outputStream->write($bytes);
        }

        return 0;
    }
131809
public function upload(String $localPath, String $remotePath, String $type = 'ascii') : Bool
    {
        if( ftp_put($this->connect, $remotePath, $localPath, Helper::toConstant($type, 'FTP_')) )
        {
            return true;
        }
        else
        {
            throw new FileRemoteUploadException($localPath);
        }
    }
757062
public function upload($destination, array $files)
    {
        foreach ($files as $file) {
            if (!($file instanceof FileEntity)) {
                // This should never occur, but it's always better not to rely on framework users
                throw new LogicException(sprintf(
                    'Each file entity must be an instance of \Krystal\Http\FileTransfer\FileInfoInterface, but received "%s"', gettype($file)
                ));
            }

            // Gotta ensure again, UPLOAD_ERR_OK means there are no errors
            if ($file->getError() == \UPLOAD_ERR_OK) {
                // Start trying to move a file
                if (!$this->move($destination, $file->getTmpName(), $file->getUniqueName())) {
                    return false;
                }
            } else {
                // Invalid file, so that cannot be uploaded. That actually should be reported before inside validator
                return false;
            }
        }

        return true;
    }
1354797
public function upload($sourceFile, $destinationFile)
    {
        $destination = $this->storagePath.rtrim($destinationFile, '/');
        Service::$log->msg('Filesystem: Copying file to the backup storage location: ' . $sourceFile);
        copy($sourceFile, $destination);
        Service::$log->msg('Filesystem: Copy ended: '.$destination);

        return $destination;
    }
1335343
private function combineFileChunks($fileUuid, $tempPath, $totalChunks, UploadedFile $originalFile)
    {
        $finalFilePath = $tempPath . DIRECTORY_SEPARATOR . $fileUuid;
        $finalFile = fopen($finalFilePath, 'wb');
        for ($i = 0; $i < $totalChunks; ++$i) {
            $chunkFile = $tempPath . DIRECTORY_SEPARATOR . $fileUuid . $i;
            $addition = fopen($chunkFile, 'rb');
            stream_copy_to_stream($addition, $finalFile);
            fclose($addition);
            unlink($chunkFile);
        }
        fclose($finalFile);

        return new UploadedFile($finalFilePath, $originalFile->getClientOriginalName());
    }
483487
public function write(string $data): int
    {
        $length = strlen($data);

        if (0 === $length) {
            return 0;
        }

        $written = @fwrite($this->handle, $data, $length);

        if (false === $written || $written !== $length) {
            $message = 'Could not write to the file.';
            if ($error = error_get_last()) {
                $message .= sprintf(' Errno: %d; %s', $error['type'], $error['message']);
            }
            throw new FileException($message);
        }

        return $written;
    }
318651
public function upload($imageFile)
    {
        if ($imageFile instanceof UploadedFile) {
            if ($imageFile->isValid()) {
                $pictureId = $this->pictureIdGenerator->generate($imageFile);
                if(false === $this->disk->putFileAs('', $imageFile, $this->pictureUrlManager->getOriginalPath($pictureId))){
                    throw new UploadException();
                }
                return $pictureId;
            } else {
                throw new UploadException($imageFile->getErrorMessage());
            }
        } else {
            throw new UploadException();
        }
    }
1373262
public function accept()
    {
        $new = stream_socket_accept(
            $this->socket,
            $this->options['timeout_accept']
        );

        if (!$new) {
            throw new ConnectionException(socket_strerror(socket_last_error($new)));
        }
        
        socket_set_option(socket_import_stream($new), SOL_TCP, TCP_NODELAY, 1);

        return $new;
    }
1250375
public static function maxUpload ($default = null)
		{
			$bytes = self::maxBytesUpload();

			return ( $bytes == null ) ? $default : self::size($bytes);
		}