Upload file to user public directory

@author Vincent Chalamon <vincentchalamon@gmail.com>
@return JsonResponse|Response
351385
public function uploadAction()
    {
        if (!$filename = $this->get('vince_type.manager.redactor')->uploadFile()) {
            return new JsonResponse(array(
                    'error' => $this->get('translator')->trans('redactor.messages.fileUploadError', array(), 'Vince'),
                )
            );
        }

        return new Response(json_encode(array(
            'filelink' => $filename,
            'filename' => pathinfo($filename, PATHINFO_FILENAME),
            ), JSON_UNESCAPED_SLASHES), 200, array(
                'Content-Type' => 'application/json',
            )
        );
    }
1020504
public function doUpload()
    {
        // CJ: Create a folder if it doesn't already exist
        if (!file_exists($this->getOption('location'))) {
            mkdir($this->getOption('location'), 0777, true);
        }

        //use the multup library to perform the upload
        $result = Multup::open('file', 'image|max:'.$this->getOption('size_limit') * 1000, $this->getOption('location'),
                                    $this->getOption('naming') === 'random')
            ->sizes($this->getOption('sizes'))
            ->set_length($this->getOption('length'))
            ->upload();

        return $result[0];
    }
116242
public function upload(Request $request)
    {
        $attachment = [];
        foreach ($request->allFiles() as $files) {
            $files = Arr::wrap($files);

            foreach ($files as $file) {
                $attachment[] = $this->createModel($file, $request);
            }
        }

        $attachment = count($attachment) > 1 ? $attachment : reset($attachment);

        return response()->json($attachment);
    }
1256228
protected function dumpJsonFile()
    {
        $jsonPath = $this->config->getJsonPath();
        $this->logger->info(sprintf('Dump submitting json file: %s', $jsonPath));

        $this->api->dumpJsonFile();

        $filesize = number_format(filesize($jsonPath) / 1024, 2); // kB
        $this->logger->info(sprintf('File size: <info>%s</info> kB', $filesize));

        return $this;
    }
714945
protected function actionUpload()
    {
        switch (htmlspecialchars($_GET['action'])) {
            case 'uploadimage':
                $this->driver->uploadDir .= DIRECTORY_SEPARATOR . 'image';
                $this->driver->maxFileSize = $this->config['imageMaxSize'];
                $this->driver->accept = $this->reAccept($this->config['imageAllowFiles']);
                $this->driver->fileName = $this->config['imageFieldName'];
                break;
            case 'uploadvideo':
                $this->driver->uploadDir .= DIRECTORY_SEPARATOR . 'video';
                $this->driver->maxFileSize = $this->config['videoMaxSize'];
                $this->driver->accept = $this->reAccept($this->config['videoAllowFiles']);
                $this->driver->fileName = $this->config['videoFieldName'];
                break;
            default:
                $this->driver->uploadDir .= DIRECTORY_SEPARATOR . 'file';
                $this->driver->maxFileSize = $this->config['fileMaxSize'];
                $this->driver->accept = $this->reAccept($this->config['fileAllowFiles']);
                $this->driver->fileName = $this->config['fileFieldName'];
        }
        $rst = $this->driver->chunkUpload();
        return $this->response($rst);
    }
377725
public function imageupload(){
		if (!Member::currentUserID()) {
			$return = array(
				'error' => 1,
				'text' => "Cannot upload there"
			);
			return Convert::raw2json($return);
		}
		if(isset($_FILES['NewImage']) && $tempfile = $_FILES['NewImage']){
			// validate //
			
			$allowed = array('jpg', 'jpeg', 'gif', 'png', 'ico');
			$nameBits = explode('.', $tempfile['name']);
			$ext = end($nameBits);
			if(!in_array(strtolower($ext), $allowed)){
				$return = array(
					'error' => 1,
					'text' => "Your image must be in jpg, gif or png format"
				);
				return Convert::raw2json($return);
			}
			
			$maxsize = $_POST['MAX_FILE_SIZE'];
			if($tempfile['size'] > $maxsize){
				$size = number_format($maxsize / 1024 / 1024, 2) . 'MB'; 
				$return = array(
					'error' => 1,
					'text' => "Your image must be smaller than $size"
				);
				return Convert::raw2json($return);
			}
			
			// upload //
			
			$upload	= new Upload;
			$file = new Image();
			$upload->loadIntoFile($tempfile, $file);
			if($upload->isError()) 
				return false;
			$file = $upload->getFile();
			$return =  array(
				'link' => $file->Link()
			);
			return Convert::raw2json($return);
		
		}else{
		 	// no file to upload
			return false;
		}
	}
390849
public function postIndex()
	{
		if ( ! Input::hasFile('file'))
		{
			return Response::json(array('error' => 'File is required'), 400);
		}

		$contents = trim(File::get(Input::file('file')->getRealPath()));

		if (substr($contents, 0, 3) !== '---')
		{
			throw new Exception('Bad Markdown Formatting');
		}

		if ( ! ($pos = strpos($contents, '---', 3)))
		{
			throw new Exception('Bad Markdown Formatting');
		}

		$frontMatter = trim(substr($contents, 3, $pos - 3));
		$contents = trim(substr($contents, $pos + 3));

		$yaml = new Parser();

		$fields = $yaml->parse($frontMatter);

		return Response::json(array(
			'fields' => $fields,
			'content' => $contents
		));
	}
812574
public function index()
    {
        try {            
            $files = $this->file->get(Input::get('pid'));
            
            return response()->json([
                'status' => 'success',
                'data' => $files,
            ]);
        }
        
        catch (Exception $e) {
            return $this->handleError($e);
        }
    }
1274790
public function actionLoadBucketData()
    {
        $this->requirePostRequest();
        $this->requireAcceptsJson();

        $request = Craft::$app->getRequest();
        $keyId = Craft::parseEnv($request->getRequiredBodyParam('keyId'));
        $secret = Craft::parseEnv($request->getRequiredBodyParam('secret'));

        try {
            return $this->asJson(Volume::loadBucketList($keyId, $secret));
        } catch (\Throwable $e) {
            return $this->asErrorJson($e->getMessage());
        }
    }
1119097
public function apiCreateFile(HTTPRequest $request)
    {
        $data = $request->postVars();

        // When creating new files, rename on conflict
        $upload = $this->getUpload();
        $upload->setReplaceFile(false);

        // CSRF check
        $token = SecurityToken::inst();
        if (empty($data[$token->getName()]) || !$token->check($data[$token->getName()])) {
            $this->jsonError(400);
            return null;
        }

        // Check parent record
        /** @var Folder $parentRecord */
        $parentRecord = null;
        if (!empty($data['ParentID']) && is_numeric($data['ParentID'])) {
            $parentRecord = Folder::get()->byID($data['ParentID']);
        }
        $data['Parent'] = $parentRecord;

        $tmpFile = $request->postVar('Upload');
        if (!$upload->validate($tmpFile)) {
            $errors = $upload->getErrors();
            $message = array_shift($errors);
            $this->jsonError(400, $message);
            return null;
        }

        // TODO Allow batch uploads
        $fileClass = File::get_class_for_file_extension(File::get_file_extension($tmpFile['name']));
        /** @var File $file */
        $file = Injector::inst()->create($fileClass);

        // check canCreate permissions
        if (!$file->canCreate(null, $data)) {
            $this->jsonError(
                403,
                _t(__CLASS__.'.CreatePermissionDenied', 'You do not have permission to add files')
            );
            return null;
        }

        $uploadResult = $upload->loadIntoFile($tmpFile, $file, $parentRecord ? $parentRecord->getFilename() : '/');
        if (!$uploadResult) {
            $this->jsonError(
                400,
                _t(__CLASS__.'.LoadIntoFileFailed', 'Failed to load file')
            );
            return null;
        }

        $file->ParentID = $parentRecord ? $parentRecord->ID : 0;
        $file->write();

        $result = [
            $this->getObjectFromData($file, false)
        ];

        return (new HTTPResponse(json_encode($result)))
            ->addHeader('Content-Type', 'application/json');
    }
776749
public function getData(): array
    {
        $uploads = [];
        //if the user is trying to upload a image
        if ($this->request->hasFiles()) {
            foreach ($this->request->getUploadedFiles() as $file) {
                $uploads[] = [
                    'name' => $file->getKey(),
                    'filename' => $file->getName(),
                    'contents' => file_get_contents($file->getTempName()),
                ];
            }

            $parseUpload = function ($request) use (&$uploads) {
                foreach ($request as $key => $value) {
                    if (is_array($value)) {
                        foreach ($value as $f => $v) {
                            $uploads[] = ['name' => $key . '[' . $f . ']', 'contents' => $v];
                        }
                    } else {
                        $uploads[] = ['name' => $key, 'contents' => $value];
                    }
                }
            };
        }

        switch ($this->request->getMethod()) {
            case 'GET':
                $queryParams = $this->request->getQuery();
                unset($queryParams['_url']);
                return ['query' => $queryParams];
                break;

            case 'POST':
                if (!$uploads) {
                    //if we dont get post send the raw
                    if (count($this->request->getPost()) > 0) {
                        return ['form_params' => $this->request->getPost()];
                    } elseif ($this->request->getJsonRawBody()) {
                        return ['json' => json_decode($this->request->getRawBody(), true)];
                    }
                    //why did we get here?
                    return ['form_params' => $this->request->getPost()];
                } else {
                    $parseUpload($this->request->getPost());
                    return ['multipart' => $uploads];
                }
                break;

            case 'PUT':
                if (!$uploads) {
                    //if we get put send it with the normal put, else send json
                    if (count($this->request->getPut()) > 0) {
                        return ['form_params' => $this->request->getPut()];
                    } elseif ($this->request->getJsonRawBody()) {
                        return ['json' => json_decode($this->request->getRawBody(), true)];
                    }
                    //why did we get here?
                    return ['form_params' => $this->request->getPut()];
                } else {
                    $parseUpload($this->request->getPut());
                    return ['multipart' => $uploads];
                }

                break;
            default:
                return [];
                break;
        }
    }
1259216
public function getUploadParams()
    {
        if ($this->type === self::TYPE_URL) {
            return [
                'json' => array_merge($this->getAdditionalAttributes(), ['file' => $this->file]),
            ];
        }

        if ($this->type === self::TYPE_MULTIPART) {
            $params[] = [
                'name' => 'file',
                'contents' => fopen($this->file, 'r'),
            ];

            foreach ($this->getAdditionalAttributes() as $key => $value) {
                $params[] = [
                    'name' => $key,
                    'contents' => $value,
                ];
            }

            return [
                'multipart' => $params
            ];
        }

        return null;
    }
1047349
public function upload(Request $request)
    {
        $json = [];
        foreach ($request->file('file') as $file) {
            $this->storage->putFile($request->get('directory'), $file);
        }

        $json['success'] = trans('admin::image.success.upload');

        return response()
            ->json($json);
    }
954286
public function actionUpload()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        $model = new Mediafile();
        $routes = $this->module->routes;
        $rename = $this->module->rename;
	    $tagIds = Yii::$app->request->post('tagIds');

	    if ($tagIds !== 'undefined') {
		    $model->setTagIds(explode(',', $tagIds));
	    }

        $model->saveUploadedFile($routes, $rename);
        $bundle = FilemanagerAsset::register($this->view);

        if ($model->isImage()) {
            $model->createThumbs($routes, $this->module->thumbs);
        }

        $response['files'][] = [
            'url'           => $model->url,
            'thumbnailUrl'  => $model->getDefaultThumbUrl($bundle->baseUrl),
            'name'          => $model->filename,
            'type'          => $model->type,
            'size'          => $model->file->size,
            'deleteUrl'     => Url::to(['file/delete', 'id' => $model->id]),
            'deleteType'    => 'POST',
        ];

        return $response;
    }
1175158
public function fileAction()
	{
		if( config( 'shop.authorize', true ) ) {
			$this->authorize( 'admin', [JqadmController::class, ['admin', 'editor']] );
		}

		$contents = '';
		$files = array();
		$aimeos = app( 'aimeos' )->get();
		$type = Route::input( 'type', Input::get( 'type', 'js' ) );

		foreach( $aimeos->getCustomPaths( 'admin/jqadm' ) as $base => $paths )
		{
			foreach( $paths as $path )
			{
				$jsbAbsPath = $base . '/' . $path;
				$jsb2 = new \Aimeos\MW\Jsb2\Standard( $jsbAbsPath, dirname( $jsbAbsPath ) );
				$files = array_merge( $files, $jsb2->getFiles( $type ) );
			}
		}

		foreach( $files as $file )
		{
			if( ( $content = file_get_contents( $file ) ) !== false ) {
				$contents .= $content;
			}
		}

		$response = response( $contents );

		if( $type === 'js' ) {
			$response->header( 'Content-Type', 'application/javascript' );
		} elseif( $type === 'css' ) {
			$response->header( 'Content-Type', 'text/css' );
		}

		return $response;
	}
1286233
protected function getUploadTempFile()
    {
        $sUploadDir = $this->getOption('upload.default.dir');
        $sUploadDir = rtrim(trim($sUploadDir), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
        $sUploadDir .= 'tmp' . DIRECTORY_SEPARATOR;
        $sUploadTempFile = $sUploadDir . $this->sTempFile . '.json';
        if(!is_readable($sUploadTempFile))
        {
            throw new \Jaxon\Exception\Error($this->trans('errors.upload.access'));
        }
        return $sUploadTempFile;
    }
11125
protected function uploadFileToCloudinary($file, $publicId)
    {
        $result = $this->uploader->upload(
            $file->getRealPath(),
            [
                'public_id' => $publicId,
            ]
        );

        return $result;
    }