GithubHelp home page GithubHelp logo

siriusphp / upload Goto Github PK

View Code? Open in Web Editor NEW
224.0 224.0 27.0 151 KB

Framework agnostic upload handler library

Home Page: http://www.sirius.ro/php/sirius/upload/

License: MIT License

PHP 100.00%
file-upload forms php upload

upload's People

Contributors

adrianmiu avatar ao2 avatar bobdenotter avatar deining avatar gwendolenlynch avatar hybridvision avatar jarjak avatar moln avatar yaayes avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

upload's Issues

how we can show Error Message

how we can show error message .
i do it by
$messages = $Result->getMessages();
but not show any thing.
by var_dump show this:
array(1) { [0]=> object(Sirius\Validation\ErrorMessage)#39 (2) { ["template":protected]=> string(89) "MY ERROR MESSAGE" ["variables":protected]=> array(3) { ["allowed"]=> array(3) { [0]=> string(3) "jpg" [1]=> string(3) "png" [2]=> string(4) "jpeg" } ["image_types"]=> string(14) "JPG, PNG, JPEG" ["value"]=> array(6) { ["name"]=> string(36) "d88e7a4e8d71be8dd949cff875004bfa.gif" ["type"]=> string(9) "image/gif" ["tmp_name"]=> string(45) "C:\Users\seven\AppData\Local\Temp\phpD08D.tmp" ["error"]=> int(0) ["size"]=> int(128421) ["original_name"]=> string(22) "ajax-loading-large.gif" } } } }

how can fix this problem?

hello @adrianmiu

i installed this class with composer but when upload image this message is appear

screenshot

this is my code:

<?php
require __DIR__ . '/vendor/autoload.php';
use Sirius\Upload\Handler as UploadHandler;

if (isset($_POST['btn_upload'])) {


    $uploadHandler = new UploadHandler($_SERVER['DOCUMENT_ROOT'] . "/assets");

// set up the validation rules
    $uploadHandler->addRule('extension', ['allowed' => 'jpg', 'jpeg', 'png'], '{label} should be a valid image (jpg, jpeg, png)', 'Profile picture');
    $uploadHandler->addRule('size', ['max' => '20M'], '{label} should have less than {max}', 'Profile picture');
    $uploadHandler->addRule('imageratio', ['ratio' => 1], '{label} should be a sqare image', 'Profile picture');
    $result = $uploadHandler->process($_FILES['upload']); // ex: subdirectory/my_headshot.png
    if ($result->isValid()) {
        try {

            // do something with the image like attaching it to a model etc
            $profile->picture = $result->name;
            $profile->save();
            $result->confirm(); // this will remove the .lock file

        } catch (\Exception $e) {

            // something wrong happened, we don't need the uploaded files anymore
            $result->clear();
            throw $e;

        }
    } else {

        // image was not moved to the container, where are error messages
        $messages = $result->getMessages();

    }
}

?> 

thank you for great work!
sorry for bad english

upload files that are not images

Hi all,
I'm trying to implement sirius upload to uploa PDF files in a form, but eventhough I added the 'pdf' extension to the permitted files lists, it still gives me back an error saying the file "should be a valid image (jpg, jpeg, png)"

Doesn't the library allow other types of file or am I doing something wrong?

Thanks for the great work; hope for an answer soon

Upload multiple files

How I can manage multiple files upload? I need to do some operations when each single file is uploaded, I've read the documentation and I've added the upload aggregator but it's not clear if I need to iterate over the PSR-7 UploadedFileInterface $request->getUploadedFiles() object provided by Slim 4 or if the aggregator will take care of this and I can simply do my operations on the uploaded files one time after the $result->isValid() return a true value.

$app->post('/upload', function(Request $request, Response $response){

    $uploadHandler = new UploadHandler(TMPDIR);
    $uploadHandler->addRule('extension', ['allowed' => ['jpg', 'jpeg', 'png']]);
    $uploadHandlerAggregate = new UploadHandlerAggregate();
    $uploadHandlerAggregate->addHandler('images', $uploadHandler);
    
    $result = $uploadHandlerAggregate->process( $request->getUploadedFiles() );
    
    if( $result->isValid() ){
        $result->confirm();
        // File operations code here
    }
    
    return $response;
});

Wrong array definition for extension allowed in readme.md

This is print_r example when trying to upload PNG image with "siriusphp/upload": "~1.3" in composer.json.

// not working extension config from readme.md
$uploadHandler->addRule('extension', ['allowed' => 'jpg', 'jpeg', 'png'], '{label} should be a valid image (jpg, jpeg, png)', 'Profile picture');

The problem is when trying to match if image extension .png is allowed, it is not found because allow array looks wrong:

Sirius\Validation\Rule\Upload\Extension Object
(
    [options:protected] => Array
        (
            [allowed] => Array
                (
                    [0] => jpg
                )

            [0] => Array
                (
                    [0] => png
                )

            [1] => jpeg
            [label] => Profile picture
        )
    [context:protected] => 
        [messageTemplate:protected] => {label} should be a valid image (jpg, jpeg, png)
        [success:protected] => 
        [value:protected] => 
        [errorMessagePrototype:protected] => 
)
// working extension config definition array
$uploadHandler->addRule('extension', ['allowed' => 'jpg,png,jpeg' ], '{label} should be a valid image (jpg, jpeg, png)', 'Profile picture');

How allow array looks when it's working:

Sirius\Validation\Rule\Upload\Extension Object
(
    [options:protected] => Array
        (
            [allowed] => Array
                (
                    [0] => jpg
                    [1] => png
                    [2] => jpeg
                )

            [label] => Profile picture
        )

    [context:protected] => 
    [messageTemplate:protected] => {label} should be a valid image (jpg, jpeg, png)
    [success:protected] => 
    [value:protected] => 
    [errorMessagePrototype:protected] => 
)

is max size working?

i want to upload videos with size less than 200M, when i trying to upload videos with size 7,5M why still get error?
$uploadHandler->addRule('size', ['max' => '200M'], '{label} should have less than {max}', 'Content'); ;

function to customize the entire file name ?

Sometimes you don't want the original file name to be a part of the uploaded file name, is there a function to set the entire file name manualy, i already use setSanitizerCallback(), but it just concatenate the return value with the original name.

sorry for my English

Division by zero

hi @adrianmiu and thank you for response

my issue is when upload non image file this warning is appear.
screenshot

$uploadHandler->addRule('imageratio', ['ratio' => 1], '{label} should be a sqare image', 'pic');

and another question is how can i show error message in your sample
$messages = $result->getMessages();

and show me with sample how can i set required rule for file input

sorry for many questions i asked.

thank you so much

Setting Validation Messages for imagewidth rule

Hi,
I have to say first: this is a great library. .lock solution is a killing feature. Thank you.

I need to set validation messages in my own language for imagewidth and imageheight rule. There are two messages can be shown. One is for min and other is for max. How can we set it?

$uploadHandler->addRule('imagewidth', 'min=100&max=150');

handle error message

hello @adrianmiu
I have read documentation but I did not understand anything from how to hendle object error message.

please show me how i can hendle object error message with sample

thank you so much

When I upload image I the error message throws array

I have written this on in my class;

<?php

namespace App\Controllers;

use Sirius\Upload\Handler as UploadHandler;

//import validator
use Respect\Validation\Validator as v;

class SiriusController extends Controller
{


	public function getImageUpload($request,$response){
		return $this->view->render($response,'admin-upload.twig');
	}

    public function postImageUpload($request,$response){
      $uploadHandler = new UploadHandler($_SERVER['DOCUMENT_ROOT'] . "/img");

      // set up the validation rules
      $uploadHandler->addRule('extension', ['allowed' => 'jpg', 'jpeg', 'png'], '{label} should be a valid image (jpg, jpeg, png)', 'Profile picture');
      $uploadHandler->addRule('size', ['max' => '20M'], '{label} should have less than {max}', 'Profile picture');
      $uploadHandler->addRule('imageratio', ['ratio' => 1], '{label} should be a sqare image', 'Profile picture');


      $result = $uploadHandler->process($_FILES['upload']); // ex: subdirectory/my_headshot.png

      if ($result->isValid()) {
          try {

              // do something with the image like attaching it to a model etc
              $profile->picture = $result->name;
              $profile->save();
              $result->confirm(); // this will remove the .lock file
              $this->flash->addMessage('success','Image uploaded');
              $this->flash->addMessage('info','Make sure to add the same name i.e. image.jpg as a string in other form submission');
              return $response->withRedirect($this->router->pathFor('admin.update'));

          } catch (\Exception $e) {

              // something wrong happened, we don't need the uploaded files anymore
              $result->clear();
              throw $e;

          }
      } else {

          // image was not moved to the container, where are error messages
          $messages = $result->getMessages();
          $this->flash->addMessage('error',$messages);
          return $response->withRedirect($this->router->pathFor('admin.update'));

      }
    }
}



However when I try to upload an image, the $messages prints out Array not sure what is going wrong?

Include PSR-*

Gosh, installing this package is a pain in the neck!
Please, include PSR-0 or PSR-4 support.
Actually, I installed siriusphp/upload package, but it installed siriusphp/validation.
After handling the upload package installation, it can't find the validation previously installed.
Horrible! Have you tried installing it via composer?

Rename File on Upload

Thanks for the great work.

Quick question is there any way to rename the file on upload?

thanks

Getting the File Name After Processing

Hi,

I'm wondering, how you're supposed to get the file name, after calling the $results->confirm() , if this variable is protected and don't have a getter? https://github.com/siriusphp/upload/blob/master/src/Result/File.php#L19

Your example at the README does not work anymore because $result->name is a iterator, not a item, and by looping through that iterator we will get instances of FIle /\

I don't wan't to use the callback to get the file name, because I woudn't be able to keep track of invalid files and other stuff, and even if I try, everything would end up in a mess.

It's an easy fix, so, it would be a lot helpful if you could update the project allowing direct access to the post-processed image data.

Regards

README sample throws warning

The line:

$uploadHandler->addRule('filesize', ['max' => '20M'], '{label} should have less than {max}', 'Profile picture');

throws a warning:

Warning: filesize() expects exactly 1 parameter, 4 given in /path/to/vendor/siriusphp/validation/src/Rule/Callback.php on line 49

Changing the 'filesize' to 'size' fixes the problem.

Allow access to the validator?

If you have a form with uploads that validates the data and then processes the uploads you need to be able to pass the upload errors into the validator

$formValidator->validate($_POST);
$result = $uploadHandler->process($_FILES['image']);
if (!$result->isValid()) {
    $formValidator->addMessages('image', $uploadHandler->getValidator()->getMesages();
}

simply handle all files

(how) can we simply handle all uploaded files?

im trying to migrate away from https://framework.zend.com/manual/1.11/en/zend.file.transfer.introduction.html and there we simply need to do:

$upload = new Zend_File_Transfer();
$files = $upload->getFileInfo();
foreach ($files as $file) ....

and i'm on a guest to find a same simple usage:

  • i dont have to know identifiers in $_FILES
  • i can simply loop over all uploaded files

ps. please note that the files are in $_FILES["whatever_<number>"], and cause the <number> is crucial for frontend, i cannot use whatever[]. and anyway, if i want to handle all files, there is no need for me to know their identifiers in $_FILES.

Call to undefined method Sirius\Upload\Result\File::save()

hi

can i fix this error when use upload class?
`<?php
require_once '../core/config.php';
use Sirius\Upload\Handler as UploadHandler;

if (isset($_POST['btn_upload'])) {
$uploadHandler = new UploadHandler(ROOT . 'upload-test');

// validation rules
$uploadHandler->addRule('uploadrequired');
$uploadHandler->addRule('extension', ['allowed' => ['jpg', 'jpeg', 'png']], '{label} should be a valid image (jpg, jpeg, png)', 'Profile picture');
$uploadHandler->addRule('size', ['max' => '20M'], '{label} should have less than {max}', 'Profile picture');

$result = $uploadHandler->process($_FILES['foo']); // ex: subdirectory/my_headshot.png

if ($result->isValid()) {
    // do something with the image like attaching it to a model etc
    try {
        $profile->foo = $result->name;
        $profile->save();
        $result->confirm(); // this will remove the .lock file
    } catch (\Exception $e) {
        // something wrong happened, we don't need the uploaded files anymore
        $result->clear();
        throw $e;
    }
} else {
    // image was not moved to the container, where are error messages
    $messages = $result->getMessages();

}

}
?>
<!doctype html>

<title>Document</title> `

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.