Get file params
@param UploadedFile $file
@param string $disk
@param string|null $lastModified
@param string|null $customId
@return array
420002
public function getFileParams(
        UploadedFile $file,
        string $disk,
        string $lastModified = null,
        string $customId = null
    ): array {
        $params = [];

        if ($customId) {
            $params['id'] = $customId;
        } else {
            $params['id'] = Uuid::uuid4()->toString();
        }

        // TODO test with .svg
        $extension = $this->getExtension($file);

        // TODO add extension to original when original name is not well formed
        $params['disk'] = $disk;
        $params['original_name'] = $file->getClientOriginalName();
        $params['extension'] = $extension;
        $params['safe_name'] = $params['id'] . $extension;
        $params['path'] = $this->uploadPath . $params['safe_name'];
        $params['size'] = $file->getSize();
        $params['mime_type'] = $file->getClientMimeType();
        $params['uploaded_by'] = auth()->check() ? auth()->id() : null;
        // TODO move lastModified getting to upload method as param
        $params['original_at'] = $lastModified;

        return $params;
    }
291503
private function getFileFromOptions($file, $options = [])
    {
        extract($options);

        $originalFilename = "{$file['public_id']}.{$file['format']}";
        $resizedFilename = "{$file['public_id']}_{$width}_{$height}_{$gravity}.{$file['format']}";

        $image = Image::make(Storage::get("{$this->uploadFolder}/{$originalFilename}"));

        if (!$width || !$height) {
            $image->resize($width, $height, function ($constraint) {
                $constraint->aspectRatio();
            });
        } else {
            $image->fit($width, $height);
        }

        $image->save(public_path("/{$this->mediaFolder}/{$resizedFilename}"));

        return "/{$this->mediaFolder}/{$resizedFilename}";
    }
1345629
public function getFileFromChunks(UploadedFile $uploadedFile)
    {
        $filename = time() . '-' . $uploadedFile->getClientOriginalName();
        $path = $this->tmpDir . DIRECTORY_SEPARATOR . $filename;

        if (FlowBasic::save($path, $this->tmpDir)) {
            return new UploadedFile($path, $uploadedFile->getClientOriginalName(), $uploadedFile->getClientMimeType());
        }

        return null;
    }
1140156
protected static function getFiles($file)
    {
        if (empty($file)) {
            throw new InvalidArgumentException('There is not any file defined');
        }

        if (is_string($file)) {
            if (!is_file($file)) {
                throw new InvalidArgumentException("'$file' is not a valid file");
            }

            if (!is_readable($file)) {
                throw new InvalidArgumentException("'$file' is not a readable file");
            }

            return [$file];
        }

        if (is_array($file)) {
            $files = [];

            foreach ($file as $f) {
                $files = array_merge($files, self::getFiles($f));
            }

            return $files;
        }

        throw new InvalidArgumentException('The first argument must be string or array');
    }
145125
public function getUploadPath(UploadedFile $file)
    {
        if (($path = $this->uploadPath)) {
            if (is_callable($path)) {
                $path = call_user_func($path, $file);
            }

            return trim($path, '/');
        }

        return $this->getDefaultUploadPath($file);
    }
420869
function resolveFilesInParams(params, files) {
	var fileIds = Object.keys(files || {});

	var fileCount = fileIds.length;
	if (fileCount === 0) {
		return;
	}

	// scan all members for files, and collect children

	function addMembers(list, obj) {
		var keys = Object.keys(obj || {});

		for (var i = 0; i < keys.length; i++) {
			list.push({
				owner: obj,
				key: keys[i],
				value: obj[keys[i]]
			});
		}
	}

	var list = [];

	addMembers(list, params);

	for (var i = 0; i < list.length && fileCount > 0; i++) {
		var member = list[i];

		if (!member.value) {
			continue;
		}

		var type = typeof member.value;

		if (type === 'object') {
			// append children to the end of the list

			addMembers(list, member.value);
		} else if (type === 'string' && files[member.value]) {
			// file found for this property, so assign it

			var file = files[member.value];

			logger.verbose('Accepted file', '"' + file.partName + '":', file.fileName);

			member.owner[member.key] = file;

			delete files[member.value];
			fileCount -= 1;
		}
	}
}
1047587
def get_upload_params(request):
    """"""
    file_name = request.POST['name']
    file_type = request.POST['type']
    file_size = int(request.POST['size'])

    dest = get_s3direct_destinations().get(
        request.POST.get('dest', None), None)
    if not dest:
        resp = json.dumps({'error': 'File destination does not exist.'})
        return HttpResponseNotFound(resp, content_type='application/json')

    auth = dest.get('auth')
    if auth and not auth(request.user):
        resp = json.dumps({'error': 'Permission denied.'})
        return HttpResponseForbidden(resp, content_type='application/json')

    allowed = dest.get('allowed')
    if (allowed and file_type not in allowed) and allowed != '*':
        resp = json.dumps({'error': 'Invalid file type (%s).' % file_type})
        return HttpResponseBadRequest(resp, content_type='application/json')

    cl_range = dest.get('content_length_range')
    if (cl_range and not cl_range[0] <= file_size <= cl_range[1]):
        msg = 'Invalid file size (must be between %s and %s bytes).'
        resp = json.dumps({'error': (msg % cl_range)})
        return HttpResponseBadRequest(resp, content_type='application/json')

    key = dest.get('key')
    if not key:
        resp = json.dumps({'error': 'Missing destination path.'})
        return HttpResponseServerError(resp, content_type='application/json')

    bucket = dest.get('bucket',
                      getattr(settings, 'AWS_STORAGE_BUCKET_NAME', None))
    if not bucket:
        resp = json.dumps({'error': 'S3 bucket config missing.'})
        return HttpResponseServerError(resp, content_type='application/json')

    region = dest.get('region', getattr(settings, 'AWS_S3_REGION_NAME', None))
    if not region:
        resp = json.dumps({'error': 'S3 region config missing.'})
        return HttpResponseServerError(resp, content_type='application/json')

    endpoint = dest.get('endpoint',
                        getattr(settings, 'AWS_S3_ENDPOINT_URL', None))
    if not endpoint:
        resp = json.dumps({'error': 'S3 endpoint config missing.'})
        return HttpResponseServerError(resp, content_type='application/json')

    aws_credentials = get_aws_credentials()
    if not aws_credentials.secret_key or not aws_credentials.access_key:
        resp = json.dumps({'error': 'AWS credentials config missing.'})
        return HttpResponseServerError(resp, content_type='application/json')

    upload_data = {
        'object_key': get_key(key, file_name, dest),
        'access_key_id': aws_credentials.access_key,
        'session_token': aws_credentials.token,
        'region': region,
        'bucket': bucket,
        'endpoint': endpoint,
        'acl': dest.get('acl') or 'public-read',
        'allow_existence_optimization': dest.get('allow_existence_optimization', False)
    }

    optional_params = [
        'content_disposition', 'cache_control', 'server_side_encryption'
    ]

    for optional_param in optional_params:
        if optional_param in dest:
            option = dest.get(optional_param)
            if hasattr(option, '__call__'):
                upload_data[optional_param] = option(file_name)
            else:
                upload_data[optional_param] = option

    resp = json.dumps(upload_data)
    return HttpResponse(resp, content_type='application/json')
998445
private function uploadOne(UploadedFile $file)
    {
        try {
            $uploader = new Uploader(['config' => $this->_config]);
            $uploader->up($file);
            $fileInfo = $uploader->getFileInfo();
            $result = [
                'name' => Html::encode($file->name),
                'url' => $fileInfo['url'],
                'path' => $fileInfo['url'],
                'extension' => $file->extension,
                'type' => $file->type,
                'size' => $file->size
            ];
            if ($this->onlyImage !== true) {
                $result['filename'] = $result['name'];
            }

        } catch (Exception $e) {
            $result = [
                'error' => $e->getMessage()
            ];
        }
        return $result;
    }
807353
public function getUploadFileName(UploadedFile $file)
    {
        if (! is_callable($this->uploadFileName)) {
            return $this->defaultUploadFilename($file);
        }

        return call_user_func($this->uploadFileName, $file);
    }
63141
public function getDMSFileEditFields($file)
    {

        // Empty actions, generate default
        if (empty($this->fileEditFields)) {
            $fields = $file->getCMSFields();
            // Only display main tab, to avoid overly complex interface
            if ($fields->hasTabSet() && ($mainTab = $fields->findOrMakeTab('Root.Main'))) {
                $fields = $mainTab->Fields();
            }
            return $fields;
        }

        // Fields instance
        if ($this->fileEditFields instanceof FieldList) {
            return $this->fileEditFields;
        }

        // Method to call on the given file
        if ($file->hasMethod($this->fileEditFields)) {
            return $file->{$this->fileEditFields}();
        }

        user_error("Invalid value for UploadField::fileEditFields", E_USER_ERROR);
    }
633335
public function toArray($import, $file, string $disk = null, string $readerType = null): array
    {
        $filePath = ($file instanceof UploadedFile) ? $file->getFilename() : $file;

        $this->imported[$disk ?? 'default'][$filePath] = $import;

        return [];
    }
1314658
public static function get_files_parameters() {
        return new external_function_parameters(
            array(
                'contextid'    => new external_value(PARAM_INT, 'context id Set to -1 to use contextlevel and instanceid.'),
                'component'    => new external_value(PARAM_TEXT, 'component'),
                'filearea'     => new external_value(PARAM_TEXT, 'file area'),
                'itemid'       => new external_value(PARAM_INT, 'associated id'),
                'filepath'     => new external_value(PARAM_PATH, 'file path'),
                'filename'     => new external_value(PARAM_TEXT, 'file name'),
                'modified'     => new external_value(PARAM_INT, 'timestamp to return files changed after this time.', VALUE_DEFAULT, null),
                'contextlevel' => new external_value(PARAM_ALPHA, 'The context level for the file location.', VALUE_DEFAULT, null),
                'instanceid'   => new external_value(PARAM_INT, 'The instance id for where the file is located.', VALUE_DEFAULT, null)

            )
        );
    }
1344939
public function download(
        string $source,
        string $disk = null,
        string $customId = null,
        string $mimeType = null
    ): ?array {
        // TODO maybe we should add exceptions instead of returning null values?
        if ($customId) {
            if ($resource = $this->getRepository()->find($customId)) {
                return $resource->toArray();
            }
        }

        $fileName = $this->getFileName($source);

        if (!strlen($fileName)) {
            return null;
        }

        $this->createFolder('uploads/tmp', 'local');

        $destination = storage_path('app/uploads/tmp/' . $fileName);

        file_put_contents($destination, file_get_contents($source));

        if (filesize($destination) <= config('resources.max_checksum_size')) {
            $resource = $this->getRepository()->findOneBy(['checksum' => hash_file('sha256', $destination)]);

            if (!$this->allowDuplicates && $resource) {
                //If duplicate found deleting downloaded file
                unlink($destination);

                return $resource->toArray();
            }
        }

        if (!file_exists($destination)) {
            return null;
        }

        if (!$mimeType) {
            $mimeType = mime_content_type($destination);
        }

        $file = new UploadedFile($destination, $fileName, $mimeType, filesize($destination), null, true);

        return $this->upload($file, null, $disk, $customId);
    }
867555
protected function getUploadedFilename(UploadedFile $file): string
    {
        $extension = $file->getClientOriginalExtension();

        return \sprintf('%s.%s', Str::random(10), $extension);
    }
502215
public static function fileChanged($file, $etag = null, $lastmodifiedheader = null) {

        if ($etag) {
            return HttpIfModifiedSince::eTagChanged($file, $etag);
        }

        if ($lastmodifiedheader) {
            return HttpIfModifiedSince::isModified($file, $lastmodifiedheader);
        }

        return true;
    }
1213518
protected function prepareUploadData(UploadedFile $uploadedFile)
    {
        return [
            'extension' => $uploadedFile->getClientOriginalExtension(),
            'mimetype'  => $uploadedFile->getMimeType(),
            'size'      => $uploadedFile->getSize(),
            'name'      => $uploadedFile->getClientOriginalName(),
        ];
    }
1011250
private function getExtension(UploadedFile $file): ?string
    {
        $originalName = $file->getClientOriginalName();

        if ($extension = pathinfo($originalName, PATHINFO_EXTENSION)) {
            return strtolower($extension);
        }

        if ($extension = $file->guessExtension()) {
            return strtolower($extension);
        }

        return null;
    }