Post an image from the admin

@return Json
177001
public function postImage()
	{
		$file = Input::file('file');
		$imageDir = Config::get('core::wardrobe.image_dir');
		$destinationPath = public_path(). "/{$imageDir}/";
		$filename = $file->getClientOriginalName();
		$resizeEnabled = Config::get('core::wardrobe.image_resize.enabled');
		
		if ($resizeEnabled)
		{
			$resizeWidth = Config::get('core::wardrobe.image_resize.width');
			$resizeHeight = Config::get('core::wardrobe.image_resize.height');
			$image = Image::make($file->getRealPath())->resize($resizeWidth, $resizeHeight, true);
			$image->save($destinationPath.$filename);
		}
		else
		{
			$file->move($destinationPath, $filename);
		}

		if (File::exists($destinationPath.$filename))
		{
			// @note - Using the absolute url so it loads images when ran in sub folder
			// this will make exporting less portable and may need to re-address at a later point.
			return Response::json(array('filename' => url("/{$imageDir}/".$filename)));
		}
		return Response::json(array('error' => 'Upload failed. Please ensure your public/img directory is writable.'));
	}
995850
public function getPostCreateAdmin()
    {
        $this->di->get("auth")->isAdmin(true);

        $title      = "Admin - Skapa en ny användare";
        $card       = "Användarinformation";
        $view       = $this->di->get("view");
        $pageRender = $this->di->get("pageRender");
        $form       = new CreateAdminForm($this->di);

        $form->check();

        $data = [
            "form" => $form->getHTML(),
            "title" => $title,
            "card" => $card
        ];

        $view->add("admin/create", $data);

        $pageRender->renderPage(["title" => $title]);
    }
996485
public function getJson()
    {
        $json = array(
            'urlKeyParam' => $this->getUrlKeyParam(),
            'inputFieldName' => $this->getTokenInputName(),
            'observedCssRules' => $this->getObservedCssRules(),
            'requestUrl' => $this->getTokenUrl(),
            'cookieName' => $this->getCookieName()
        );

        return json_encode($json);
    }
414413
public function cropAction ()
    {
        $this->validateRequest();
        
        $imageManager = $this->container->get('thrace_media.imagemanager');
        $name = $this->getRequest()->get('name');
        $options = array();
        
        $options['x'] = $this->getRequest()->get('x', false);
        $options['y'] = $this->getRequest()->get('y', false);
        $options['w'] = $this->getRequest()->get('w', false);
        $options['h'] = $this->getRequest()->get('h', false);
        
        if (!$imageManager->crop($name, $options)){
            return new JsonResponse(array(
                'success' => false,
                'err_msg' => $this->container->get('translator')
                    ->trans('error.image_crop', array('name' => $name), 'ThraceMediaBundle')
            ));
        }
       
        $hash = $imageManager->checksumTemporaryFileByName($name);
        
        return new JsonResponse(array(
            'success' => true,
            'name'    => $name,
            'hash'    => $hash
        ));
    }
34124
public function upload()
    {
        $position = $this->request->getQuery('position');
        $positions = $this->viewVars['positions']->toArray();

        //If there's only one available position
        if (!$position && count($positions) < 2) {
            $position = array_key_first($positions);
            $this->request = $this->request->withQueryParams(compact('position'));
        }

        if ($this->request->getData('file')) {
            is_true_or_fail($position, __d('me_cms', 'Missing ID'), InternalErrorException::class);

            $uploaded = $this->Uploader->set($this->request->getData('file'))
                ->mimetype('image')
                ->save(BANNERS);

            if (!$uploaded) {
                return $this->setUploadError($this->Uploader->getError());
            }

            $entity = $this->Banners->newEntity([
                'position_id' => $position,
                'filename' => basename($uploaded),
            ]);

            if ($entity->getErrors()) {
                return $this->setUploadError(array_value_first_recursive($entity->getErrors()));
            }

            if (!$this->Banners->save($entity)) {
                $this->setUploadError(I18N_OPERATION_NOT_OK);
            }
        }
    }
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;
		}
	}
901075
public function uploadAction()
    {
        $authenticationService = $this->getServiceLocator()->get('zfcuser_auth_service');
        if (!$authenticationService->hasIdentity()) {
            return $this->redirect()->toRoute('zfcuser');
        }

        $user = $this->getUser();
        if (!$user) {
            return $this->notFoundAction();
        }
        $options = $this->getOptions();
        $form = $this->getServiceLocator()->get('HtProfileImage\ProfileImageForm');
        /** @var \Zend\Http\Request $request */
        $request = $this->getRequest();
        $imageUploaded = false;
        if ($request->isPost()) {
            $negotiator   = new FormatNegotiator();
            $format = $negotiator->getBest(
                $request->getHeader('Accept')->getFieldValue(),
                ['application/json', 'text/html']
            );
            if ($this->profileImageService->storeImage($user, $request->getFiles()->toArray())) {
                if ($format->getValue() === 'application/json') {
                    return new Model\JsonModel([
                        'uploaded' => true
                    ]);
                } elseif ($options->getPostUploadRoute()) {
                        return call_user_func_array([$this->redirect(), 'toRoute'], (array) $options->getPostUploadRoute());
                }
                $imageUploaded = true;
            } else {
                $response = $this->getResponse();
                /** @var \Zend\Http\Response $response */
                $response->setStatusCode(400);
                if ($format->getValue() === 'application/json') {
                    return new Model\JsonModel([
                        'error' => true,
                        'messages' => $form->getMessages()
                    ]);
                }

            }
        }

        return new Model\ViewModel([
            'form' => $form,
            'imageUploaded' => $imageUploaded,
            'user' => $user
        ]);
    }
333999
public function json() : string
    {
        return json_encode([
            'title' => $this->title,
            'body' => $this->body,
            'url' => $this->url,
            'icon' => $this->icon,
        ]);
    }
981835
public function image() {
		if (Request::hasFile('image') && Request::has('table_name') && Request::has('field_name')) {
			return json_encode(self::saveImage(
				Request::input('table_name'), 
				Request::input('field_name'), 
				Request::file('image'),
				null,
				Request::file('image')->getClientOriginalExtension()
			));
		} elseif (!Request::hasFile('image')) {
			return 'no image';
		} elseif (!Request::hasFile('table_name')) {
			return 'no table_name';
		} elseif (!Request::hasFile('field_name')) {
			return 'no field_name';
		}
	}
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);
    }
952961
public function store()
    {
        // TODO: to clean

        if (!Input::hasFile('file')) {
            return $this->jsonErrorResponse('"file" is required.');
        }

        Subbly::events()->fire('subbly.upload:creating', array());

        $file      = Input::file('file');
        $file_type = Input::get('file_type', 'product_image');

        $destination = app_upload($file_type);
        $publicPath  = public_upload($file_type);
        $filename    = sprintf('%s.%s',
            uniqid(),
            $file->getClientOriginalExtension()
        );

        $inputFile = Input::all();

        unset($inputFile['file']);

        $fileData = array(
          'file' => array_merge($inputFile, array(
              'filename'  => $filename, 'file_path' => sprintf('%s/%s', $publicPath, $filename),
          )),
        );

        $uploadSuccess = $file->move($destination, $filename);

        if ($uploadSuccess) {
            Subbly::events()->fire('subbly.upload:created', $fileData);
        } else {
            Subbly::events()->fire('subbly.upload:error', $fileData);
        }

        return $this->jsonResponse($fileData,
        array(
            'status' => array(
                'code'    => 201,
                'message' => 'Upload done',
            ),
        ));
    }
850498
protected function _getJsonRpcRequest() {
        if ($this->getRequest()->getPost('request')) {
            return $this->getRequest()->getPost('request');
        }
        return $request = $this->getRequest()->getRawBody();
    }
703925
public function actionIndex()
    {
        $result = [
            'content' => false,
            'response' => 'error',
        ];

        $params = Json::decode(Craft::$app->request->getRawBody());
        $config = $params['params'] ?? [];
        $uri = $params['uri'];

        if (($uri ?? false)) {
            $config['includeAssets'] = false;

            $result['content'] = AdminBar::$plugin->bar->renderAdminBarForUri($uri, $config);
            if (!empty($result['content'])) {
                $result['response'] = 'success';
            }
        }

        return $this->asJson($result);
    }
930473
public function jsonResponse()
    {
        $user = Auth::getUser();

        //Change here whatever you need
        $ssoUser = new SSOUser();
        $ssoUser->id = $user->id;
        $ssoUser->name = $user->username;
        $ssoUser->email = $user->email;
        $ssoUser->roles = $user->roles;
        $ssoUser->profilepicture = "";

        $userInfo = $ssoUser->toArray();

        return VanillaSSO::WriteJsConnect($userInfo, $_GET, true);
    }
767699
def admin_update
      return unless user_is_allowed('categories', 'edit')
      
      # Define category and initialize response
      category = Category.find(params[:id])
      response = { attributes: Hash.new }
      
      # Iterate over params and update relevant attributes
      params.each do |key, value|
        case key
        when 'name' then category.name = value
        when 'slug' then category.slug = value
        when 'status' then category.status = value
        when 'image' then category.image = value
        end
      end
      
      # Try and save category
      response[:success] = category.save
      
      # If an image is passed, return the url
      response[:attributes][:image] = { value: category.image.url(:medium) } if params[:image]
      
      # Respond to update request
      render :json => response
    end
84487
public function actionDeleteImage(): Response
    {
        $model = $this->findModel($this->attachmentModelClass, Yii::$app->request->post('id'));

        $model->delete();

        return $this->asJson([
            'status' => 'success',
        ]);
    }
182326
public function getPostFromInput()
    {
        $ct = $_SERVER['CONTENT_TYPE'];
        $position = stripos($ct, "boundary=");
        $jsonCheck = "application/json";

        $input = file_get_contents("php://input");

        $this->rawData = $input;

        $postVars = array();
        if ($position !== false) {

            $exp = explode("boundary=", $ct);
            if (isset($exp[1])) {
                $boundary = trim($exp[1]);

                $variables = explode("--" . $boundary, $input);

                foreach ($variables as $var) {
                    $var = urldecode($var);
                    if (trim($var) != "" && trim($var) != "--") {
                        preg_match('/Content-Disposition:[ _]*form-data;[ _]*name="([^\"]*)"(.*)/si', $var, $result);
                        $postVars[trim($result[1])] = trim($result[2]);
                    }
                }
            }
        } else if (substr($ct, 0, strlen($jsonCheck)) === $jsonCheck) {
            $postVars = json_decode($input, true);
        } else {
            parse_str($input, $postVars);
        }

        if (count($_POST) > 0 && count($postVars) === 0) {
            $postVars = $_POST;
        }

        return $postVars;
    }