You are here

public function UploadHandler::handleUpload in DropzoneJS 8.2

Same name and namespace in other branches
  1. 8 src/UploadHandler.php \Drupal\dropzonejs\UploadHandler::handleUpload()

Handles an uploaded file.

Parameters

\Symfony\Component\HttpFoundation\File\UploadedFile $file: The uploaded file.

Return value

string URI of the uploaded file.

Throws

\Drupal\dropzonejs\UploadException

Overrides UploadHandlerInterface::handleUpload

File

src/UploadHandler.php, line 113

Class

UploadHandler
Handles files uploaded by Dropzone.

Namespace

Drupal\dropzonejs

Code

public function handleUpload(UploadedFile $file) {
  $error = $file
    ->getError();
  if ($error != UPLOAD_ERR_OK) {

    // Check for file upload errors and return FALSE for this file if a lower
    // level system error occurred. For a complete list of errors:
    // See http://php.net/manual/features.file-upload.errors.php.
    switch ($error) {
      case UPLOAD_ERR_INI_SIZE:
      case UPLOAD_ERR_FORM_SIZE:
        $message = $this
          ->t('The file could not be saved because it exceeds the maximum allowed size for uploads.');
        break;
      case UPLOAD_ERR_PARTIAL:
      case UPLOAD_ERR_NO_FILE:
        $message = $this
          ->t('The file could not be saved because the upload did not complete.');
        break;

      // Unknown error.
      default:
        $message = $this
          ->t('The file could not be saved. An unknown error has occurred.');
        break;
    }
    throw new UploadException(UploadException::FILE_UPLOAD_ERROR, $message);
  }

  // Open temp file.
  $tmp = $this->dropzoneSettings
    ->get('tmp_upload_scheme') . '://' . $this
    ->getFilename($file);
  if (!($out = fopen($tmp, $this->request->request
    ->get('chunk', 0) ? 'ab' : 'wb'))) {
    throw new UploadException(UploadException::OUTPUT_ERROR);
  }

  // Read binary input stream.
  $input_uri = $file
    ->getFileInfo()
    ->getRealPath();
  if (!($in = fopen($input_uri, 'rb'))) {
    throw new UploadException(UploadException::INPUT_ERROR);
  }

  // Append input stream to temp file.
  while ($buff = fread($in, 4096)) {
    fwrite($out, $buff);
  }

  // Be nice and keep everything nice and clean. Initial uploaded files are
  // automatically removed by PHP at the end of the request so we don't need
  // to do that.
  // @todo when implementing multipart don't forget to drupal_unlink.
  fclose($in);
  fclose($out);
  return $tmp;
}