function FileUploadResource::streamUploadData

Same name in other branches
  1. 8.9.x core/modules/file/src/Plugin/rest/resource/FileUploadResource.php \Drupal\file\Plugin\rest\resource\FileUploadResource::streamUploadData()
  2. 10 core/modules/file/src/Plugin/rest/resource/FileUploadResource.php \Drupal\file\Plugin\rest\resource\FileUploadResource::streamUploadData()

Streams file upload data to temporary file and moves to file destination.

Return value

string The temp file path.

Throws

\Symfony\Component\HttpKernel\Exception\HttpException Thrown when input data cannot be read, the temporary file cannot be opened, or the temporary file cannot be written.

1 call to FileUploadResource::streamUploadData()
FileUploadResource::post in core/modules/file/src/Plugin/rest/resource/FileUploadResource.php
Creates a file from an endpoint.

File

core/modules/file/src/Plugin/rest/resource/FileUploadResource.php, line 336

Class

FileUploadResource
File upload resource.

Namespace

Drupal\file\Plugin\rest\resource

Code

protected function streamUploadData() {
    // 'rb' is needed so reading works correctly on Windows environments too.
    $file_data = fopen('php://input', 'rb');
    $temp_file_path = $this->fileSystem
        ->tempnam('temporary://', 'file');
    $temp_file = fopen($temp_file_path, 'wb');
    if ($temp_file) {
        while (!feof($file_data)) {
            $read = fread($file_data, static::BYTES_TO_READ);
            if ($read === FALSE) {
                // Close the file streams.
                fclose($temp_file);
                fclose($file_data);
                $this->logger
                    ->error('Input data could not be read');
                throw new HttpException(500, 'Input file data could not be read');
            }
            if (fwrite($temp_file, $read) === FALSE) {
                // Close the file streams.
                fclose($temp_file);
                fclose($file_data);
                $this->logger
                    ->error('Temporary file data for "%path" could not be written', [
                    '%path' => $temp_file_path,
                ]);
                throw new HttpException(500, 'Temporary file data could not be written');
            }
        }
        // Close the temp file stream.
        fclose($temp_file);
    }
    else {
        // Close the input file stream since we can't proceed with the upload.
        // Don't try to close $temp_file since it's FALSE at this point.
        fclose($file_data);
        $this->logger
            ->error('Temporary file "%path" could not be opened for file upload', [
            '%path' => $temp_file_path,
        ]);
        throw new HttpException(500, 'Temporary file could not be opened');
    }
    // Close the input stream.
    fclose($file_data);
    return $temp_file_path;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.