IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Bibliothèques et frameworks PHP Discussion :

CakePHP 2 - Upload fichier [CakePHP]


Sujet :

Bibliothèques et frameworks PHP

  1. #1
    Membre du Club
    Profil pro
    Inscrit en
    Février 2011
    Messages
    93
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2011
    Messages : 93
    Points : 63
    Points
    63
    Par défaut CakePHP 2 - Upload fichier
    Bonjour,

    J'ai du mal à trouver comment on upload un fichier depuis un formulaire à la "mode" cakephp 2... j'ai essayé des plugins comme celui-là qui me paraît très bien : http://milesj.me/code/cakephp/uploader
    Mais par exemple si j'utilise ce plugin $data me renvoix toujours false...

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
     
    public function upload() {
    	if (!empty($this->data)) {
    		if ($data = $this->Uploader->upload('fileName')) {
    			// Upload successful, do whatever
    		}
    	}
    }
    Est ce que si quelqu'un a déjà utilisé ce plugin ou aurait fait d'une autre façon je suis preneur...

  2. #2
    Membre du Club
    Profil pro
    Inscrit en
    Février 2011
    Messages
    93
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2011
    Messages : 93
    Points : 63
    Points
    63
    Par défaut
    Problème résolu j'ai enfin réussi à utiliser le plugin !

  3. #3
    Membre à l'essai
    Femme Profil pro
    Développeur Web
    Inscrit en
    Mars 2016
    Messages
    8
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Algérie

    Informations professionnelles :
    Activité : Développeur Web

    Informations forums :
    Inscription : Mars 2016
    Messages : 8
    Points : 10
    Points
    10
    Par défaut msg d'erreur avec le plugin uploader cakephp 2
    Bonjour n
    pourriez vous me dire comment vous avez reglé le pb; j'ai le mm problème que vous avec ce plugin j'arrive à uploader limage mais j'ai ce msg d'erreur
    ( ! ) Fatal error: Maximum execution time of 120 seconds exceeded in C:\wamp\www\Development\app\Plugin\Uploader\Vendor\Uploader.php on line 527
    merci pour votre aide

  4. #4
    Membre du Club
    Profil pro
    Inscrit en
    Février 2011
    Messages
    93
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2011
    Messages : 93
    Points : 63
    Points
    63
    Par défaut
    Bonjour,

    Ca resemble plus à un problème dû à un gros fichier.
    Quelle est la taille du fichier uploadé ?
    Pouvez vous essayer avec un fichier plus petit ou sinon augmenter la max_execution time (http://php.net/manual/fr/function.set-time-limit.php).

  5. #5
    Membre à l'essai
    Femme Profil pro
    Développeur Web
    Inscrit en
    Mars 2016
    Messages
    8
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Algérie

    Informations professionnelles :
    Activité : Développeur Web

    Informations forums :
    Inscription : Mars 2016
    Messages : 8
    Points : 10
    Points
    10
    Par défaut
    rebonjour


    oui j'ai ajouter la time de l'execution du cout j'ai eu un autre msg d'erreur le voici
    Array to string conversion [CORE\Cake\Model\Datasource\DboSource.php, line 1007]

    [CakeException] Headers already sent in C:\wamp\www\Development\lib\Cake\Utility\Debugger.php on line 801 #0 C:\wamp\www\Development\lib\Cake\Network\CakeResponse.php(419): CakeResponse->_sendHeader('HTTP/1.1 500 In...') #1 C:\wamp\www\Development\lib\Cake\Error\ExceptionRenderer.php(327): CakeResponse->send() #2 C:\wamp\www\Development\lib\Cake\Error\ExceptionRenderer.php(306): ExceptionRenderer->_outputMessageSafe('error500') #3 C:\wamp\www\Development\lib\Cake\Error\ExceptionRenderer.php(210): ExceptionRenderer->_outputMessage('fatalError') #4 [internal function]: ExceptionRenderer->_cakeError(Object(FatalErrorException)) #5 C:\wamp\www\Development\lib\Cake\Error\ExceptionRenderer.php(187): call_user_func_array(Array, Array) #6 C:\wamp\www\Development\lib\Cake\Error\ErrorHandler.php(119): ExceptionRenderer->render() #7 [internal function]: ErrorHandler::handleException(Object(FatalErrorException)) #8 C:\wamp\www\Development\lib\Cake\Error\ErrorHandler.php(252): call_user_func('ErrorHandler::h...', Object(FatalErrorException)) #9 C:\wamp\www\Development\lib\Cake\Error\ErrorHandler.php(203): ErrorHandler::handleFatalError(256, '[CakeException]...', 'C:\\wamp\\www\\Dev...', 128) #10 [internal function]: ErrorHandler::handleError(256, '[CakeException]...', 'C:\\wamp\\www\\Dev...', 128, Array) #11
    ...
    C:\wamp\www\Development\lib\Cake\Error\ErrorHandler.php(128): trigger_error('[CakeException]...', 256) #12 [internal function]: ErrorHandler::handleException(Object(FatalErrorException)) #13 C:\wamp\www\Development\lib\Cake\Core\App.php(931): call_user_func('ErrorHandler::h...', 1, 'Maximum functio...', 'C:\\wamp\\www\\Dev...', 812, Array) #122 C:\wamp\www\Development\lib\Cake\Core\App.php(904): App::_checkFatalError() #123 [internal function]: App::shutdown() #124 {main}

    Error: An Internal Error Has Occurred.

    et quand j'ajoute ce bout de code dans mon controller

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    if (!empty($this->request->data['Car']['picture1'])) {
              $this->Uploader = new Uploader();
    			if ($data = $this->Uploader->upload('picture1', array('name' => 'uploaderFilename', 'overwrite' => true))) {
     
    			}
    		}
    j'ai l'erreur suivante ;
    getimagesize(C:\wamp\tmp\php5A56.tmp): failed to open stream: No such file or directory [APP\Plugin\Uploader\Model\Behavior\FileValidationBehavior.php, line 360]
    Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 3791202 bytes) in C:\wamp\www\Development\lib\Cake\Event\CakeEventManager.php on line 243
    j'arrive pas à résoudre le pb.
    merci de m'aider

  6. #6
    Membre du Club
    Profil pro
    Inscrit en
    Février 2011
    Messages
    93
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2011
    Messages : 93
    Points : 63
    Points
    63
    Par défaut
    Essai d'instancier de cette manière :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    $this->Uploader = new Uploader(array('tempDir' => TMP));
    Quelle est la taille du fichier uplaodé ?

  7. #7
    Membre à l'essai
    Femme Profil pro
    Développeur Web
    Inscrit en
    Mars 2016
    Messages
    8
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Algérie

    Informations professionnelles :
    Activité : Développeur Web

    Informations forums :
    Inscription : Mars 2016
    Messages : 8
    Points : 10
    Points
    10
    Par défaut
    rebonjour

    je viens d’essayer ce que vous m'avez dit et j'ai essaye aussi de mettre:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    list($width, $height) = getimagesize($_SERVER["DOCUMENT_ROOT"].$field['tmp_name']);
    au lieu de list($width, $height) = getimagesize($field['tmp_name']);

    j'ai toujours le mm msg d'erreur
    Warning (2): getimagesize(C:/wamp/www/C:\wamp\tmp\php7973.tmp): failed to open stream: Invalid argument [APP\Plugin\Uploader\Model\Behavior\FileValidationBehavior.php, line 360]
    merci d'avance

  8. #8
    Membre du Club
    Profil pro
    Inscrit en
    Février 2011
    Messages
    93
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2011
    Messages : 93
    Points : 63
    Points
    63
    Par défaut
    Le chemin vers ton fichier n'est pas bon (getimagesize(C:/wamp/www/C:\wamp\tmp\php7973.tmp).

    Tu peux faire un

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    debug($this->Uploader);die();
    Après

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    $this->Uploader = new Uploader(array('tempDir' => TMP));
    Et me retourner le résultat ?

  9. #9
    Membre à l'essai
    Femme Profil pro
    Développeur Web
    Inscrit en
    Mars 2016
    Messages
    8
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Algérie

    Informations professionnelles :
    Activité : Développeur Web

    Informations forums :
    Inscription : Mars 2016
    Messages : 8
    Points : 10
    Points
    10
    Par défaut
    voila ce que j'ai eu quand j'ai fait ce que vous m'avez dit

    \app\Controller\CarsController.php (line 379)

    null


    ya rien dans mon uploader


    voici ce que j'ai mis dans mon model


    public $actsAs = array(
    'Uploader.FileValidation' => array(
    'picture1' => array(
    'extension' => array(
    'value' => array('gif', 'jpg', 'jpeg','png'),
    'error' => 'Only gif, jpg and jpeg images are allowed!'
    ),
    'minWidth' => 200,
    'minHeight' => 200,
    'required' => true
    ),
    'import' => array(
    'required' => false
    )
    ),



    'Uploader.Attachment' => array(
    'picture1' => array(
    'name' => 'uploaderFilename',
    'uploadDir' => '/attachments/picturescar/',
    'dbColumn' => 'path',
    'maxNameLength' => 30,
    'overwrite' => true,
    'stopSave' => false,
    'transforms' => array(
    // Save additional images in the databases after transforming
    array(
    'method' => 'resize',
    'width' => 100,
    'height' => 100,
    'dbColumn' => 'path_alt'
    )
    ),
    'metaColumns' => array(
    'size' => 'filesize', // The size value will be saved to the filesize column
    'type' => 'type' // And the same for the mimetype
    )
    ),
    'import' => array(
    'uploadDir' => '/attachments/picturescar/',
    'name' => 'uploaderFilename',
    'dbColumn' => 'path_import',
    'overwrite' => true,
    'stopSave' => false,
    'transforms' => array(
    array(
    'method' => 'scale',
    'percent' => .5,
    'dbColumn' => 'path' // Overwrite the original image
    )
    )
    )
    )
    );

    et voici le code de ma vue
    <?php echo $this->Form->create('Car', array('enctype' => 'multipart/form-data')); ?>
    echo "<div class='form-group'>" . $this->Form->input('picture1', array(
    'label' => __('Picture1'),
    'class' => 'form-control filestyle',
    'type' => 'file',
    'empty' => ''
    )) . "</div>";


    et dans mon controller voici le bout de code pour enregister mon image

    if (!empty($this->request->data['Car']['picture1'])) {
    debug($this->Uploader);die();
    $this->Uploader = new Uploader(array('tempDir' => TMP));
    if ($data = $this->Uploader->upload('picture1', array('name' => 'uploaderFilename', 'overwrite' => true))) {
    //debug($data);
    }


    }


    voici le lien où j'ai téléchargé le plugin https://github.com/milesj/uploader ; j'ai téléchargé uploader 3.x c'est le plus compatible pour ma version cakephp qui est le 2.7


    merci encore

  10. #10
    Membre du Club
    Profil pro
    Inscrit en
    Février 2011
    Messages
    93
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2011
    Messages : 93
    Points : 63
    Points
    63
    Par défaut
    Il faut faire le debug après l'instanciation.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
    if (!empty($this->request->data['Car']['picture1'])) {
    $this->Uploader = new Uploader(array('tempDir' => TMP));
    debug($this->Uploader);die();
    if ($data = $this->Uploader->upload('picture1', array('name' => 'uploaderFilename', 'overwrite' => true))) {
    debug($data);
    }

  11. #11
    Membre à l'essai
    Femme Profil pro
    Développeur Web
    Inscrit en
    Mars 2016
    Messages
    8
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Algérie

    Informations professionnelles :
    Activité : Développeur Web

    Informations forums :
    Inscription : Mars 2016
    Messages : 8
    Points : 10
    Points
    10
    Par défaut
    voila ce que j'ai eu quand j'ai fait le debug

    app\Controller\CarsController.php (line 381)

    object(Uploader) {
    maxNameLength => (int) 80
    scanFile => false
    tempDir => 'C:\wamp\www\Development\app\tmp\'
    baseDir => 'C:/wamp/www/Development/app/webroot/'
    uploadDir => 'files/uploads/'
    ajaxField => ''
    [protected] _current => null
    [protected] _data => array(
    'yellow_card' => array(
    'name' => '',
    'type' => '',
    'tmp_name' => '',
    'error' => (int) 4,
    'size' => (int) 0
    ),
    'grey_card' => array(
    'name' => '',
    'type' => '',
    'tmp_name' => '',
    'error' => (int) 4,
    'size' => (int) 0
    ),
    'picture1' => array(
    'name' => 'Citroen-C4.jpg',
    'type' => 'image/jpeg',
    'tmp_name' => 'C:\wamp\tmp\php10CC.tmp',
    'error' => (int) 0,
    'size' => (int) 226676
    ),
    'picture2' => array(
    'name' => '',
    'type' => '',
    'tmp_name' => '',
    'error' => (int) 4,
    'size' => (int) 0
    ),
    'picture3' => array(
    'name' => '',
    'type' => '',
    'tmp_name' => '',
    'error' => (int) 4,
    'size' => (int) 0
    ),
    'picture4' => array(
    'name' => '',
    'type' => '',
    'tmp_name' => '',
    'error' => (int) 4,
    'size' => (int) 0
    ),
    'purchasing_attachment' => array(
    'name' => '',
    'type' => '',
    'tmp_name' => '',
    'error' => (int) 4,
    'size' => (int) 0
    )
    )
    [protected] _enabled => '1'
    [protected] _finalDir => null
    [protected] _mimeTypes => array()
    [protected] _exts => array()
    }


    moi j'utilise le plugin uploader pour picture1
    donc c ça
    'picture1' => array(
    'name' => 'Citroen-C4.jpg',
    'type' => 'image/jpeg',
    'tmp_name' => 'C:\wamp\tmp\php10CC.tmp',
    'error' => (int) 0,
    'size' => (int) 226676
    ),

    le fichier tmp existe mais la fonction list($width, $height) = getimagesize($field['tmp_name']); retur, erreur
    quoi faire

    merci bcp

  12. #12
    Membre du Club
    Profil pro
    Inscrit en
    Février 2011
    Messages
    93
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2011
    Messages : 93
    Points : 63
    Points
    63
    Par défaut
    Il faudrait que tu fasses ça :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    getimagesize($this->Uploader->_data['photo']['tmp_name'])
    Seulement l'attribut $_data est en protected du coup tu ne peux y accéder.

    Pourquoi veut tu faire le getImageSize sur le fichier temporaire ?
    Mets d'abord l'image dans ton projet, et ensuite tu fais ton getImageSIze dessus :

    Sinon pour que ton code soit plus lisible dans la discussion entoure le avec les bonnes balises (bouton #).

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    $this->Uploader = new Uploader(array('tempDir' => TMP));
                    $dataPhoto = $this->Uploader->upload('photo', array('overwrite' => true,'name' => 'photo-profile'));
                    debug(getimagesize(WWW_ROOT.$dataPhoto['path']));

  13. #13
    Membre à l'essai
    Femme Profil pro
    Développeur Web
    Inscrit en
    Mars 2016
    Messages
    8
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Algérie

    Informations professionnelles :
    Activité : Développeur Web

    Informations forums :
    Inscription : Mars 2016
    Messages : 8
    Points : 10
    Points
    10
    Par défaut
    merci pour vos réponses ,

    la fonction getImageSizeexiste dans le plugin voici comment elle est défini

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
     
    	protected function _validateImage(Model $model, $data, $type, $size = 100) {
    		foreach ($data as $fieldName => $field) {
    			if ($this->_allowEmpty($model, $fieldName, $field)) {
    				return true;
     
    			} else if (empty($field['tmp_name'])) {
    				return false;
    			}
                //die(debug ($field['tmp_name']));
    			list($width, $height) = getimagesize($field['tmp_name']);
     
    			/*if (!$file) {
    				return false;
    			}*/
     
    			//$width = $file[0];
    			//$height = $file[1];
     
    			switch ($type) {
    				case 'width':		return ($width == $size); break;
    				case 'height':		return ($height == $size); break;
    				case 'maxWidth':	return ($width <= $size); break;
    				case 'maxHeight':	return ($height <= $size); break;
    				case 'minWidth':	return ($width >= $size); break;
    				case 'minHeight':	return ($height >= $size); break;
    			}
    		}
     
    		return true;
    	}
    j'ai essayé de mettre toute cette fonction en commentaire j'ai pas eu le msg d'erreur mais l'image n'a pas été uploader , j'ai eu ça au dessous de linput de limage : There was an error uploading this file, please try again.

  14. #14
    Membre du Club
    Profil pro
    Inscrit en
    Février 2011
    Messages
    93
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2011
    Messages : 93
    Points : 63
    Points
    63
    Par défaut
    Ne modifie pas la bibliothèque.

    Si tu fais ça :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    if (!empty($this->request->data['Car']['picture1'])) {
        $this->Uploader = new Uploader(array('tempDir' => TMP));
        $data = $this->Uploader->upload('picture1', array('name' => 'uploaderFilename', 'overwrite' => true));
        if ($data) {
            $dataPhoto = $this->Uploader->upload('photo', array('overwrite' => true,'name' => 'photo-profile'));
            debug(getimagesize(WWW_ROOT.$dataPhoto['path']));
        }
    }
    Est ce que ça fonctionne ?
    Sinon je suis à court d'idée..

  15. #15
    Membre à l'essai
    Femme Profil pro
    Développeur Web
    Inscrit en
    Mars 2016
    Messages
    8
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Algérie

    Informations professionnelles :
    Activité : Développeur Web

    Informations forums :
    Inscription : Mars 2016
    Messages : 8
    Points : 10
    Points
    10
    Par défaut
    le code ne fonctionne pas ; mais si pas un pb si je mets la fonction validateimage en commentaire j'ai pas besoin d'avoir le size de limage

    le pb que j'ai maintenant c'est que limage n'arrive pas à etre uploader ya ce msg : There was an error uploading this file, please try again.
    le msg proviens du fichier AttachmentBehaviour.php (le fichier je l'ai téléchargé avec le plugin)
    voici le code du fichier
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
     
     
    <?php
    /**
     * AttachmentBehavior
     *
     * A CakePHP Behavior that attaches a file to a model, and uploads automatically, then stores a value in the database.
     *
     * @author      Miles Johnson - http://milesj.me
     * @copyright   Copyright 2006-2011, Miles Johnson, Inc.
     * @license     http://opensource.org/licenses/mit-license.php - Licensed under The MIT License
     * @link        http://milesj.me/code/cakephp/uploader
     */
     
    App::uses('Set', 'Utility');
    App::uses('String', 'Utility');
    App::uses('ModelBehavior', 'Model');
     
    App::import('Vendor', 'Uploader.S3');
    App::import('Vendor', 'Uploader.Uploader');
     
    class AttachmentBehavior extends ModelBehavior {
     
    	/**
    	 * AS3 domain snippet.
    	 */
    	const AS3_DOMAIN = 's3.amazonaws.com';
     
    	/**
    	 * Uploader instance.
    	 *
    	 * @access public
    	 * @var Uploader
    	 */
    	public $uploader = null;
     
    	/**
    	 * S3 instance.
    	 *
    	 * @access public
    	 * @var S3
    	 */
    	public $s3 = null;
     
    	/**
    	 * All user defined attachments; images => model.
    	 *
    	 * @access protected
    	 * @var array
    	 */
    	protected $_attachments = array();
     
    	/**
    	 * Mapping of database columns to form fields.
    	 *
    	 * @access protected
    	 * @var array
    	 */
    	protected $_columns = array();
     
    	/**
    	 * The default settings for attachments.
    	 *
    	 * @access protected
    	 * @var array
    	 */
    	protected $_defaults = array(
    		'name' => '',
    		'baseDir' => '',
    		'uploadDir' => '',
    		'append' => '',
    		'prepend' => '',
    		'dbColumn' => 'uploadPath',
    		'importFrom' => '',
    		'defaultPath' => '',			// Default file path to be used if the field is empty
    		'maxNameLength' => null,
    		'overwrite' => false,			// Overwrite a file with the same name if it exists
    		'stopSave' => true,				// Stop model save() on form upload error
    		'allowEmpty' => true,			// Allow an empty file upload to continue
    		'saveAsFilename' => false,		// If true, will only save the filename and not relative path
    		'transforms' => array(),
    		's3' => array(
    			'format' => 'http://{host}/{bucket}/{path}',
    			'accessKey' => '',
    			'secretKey' => '',
    			'ssl' => true,
    			'bucket' => '',
    			'path' => '',
    			'host' => self::AS3_DOMAIN
    		),
    		'metaColumns' => array(
    			'ext' => '',
    			'type' => '',
    			'size' => '',
    			'group' => '',
    			'width' => '',
    			'height' => '',
    			'filesize' => ''
    		)
    	);
     
    	/**
    	 * Initialize uploader and save attachments.
    	 *
    	 * @access public
    	 * @param Model $model
    	 * @param array $config
    	 * @return void
    	 */
    	public function setup(Model $model, $config = array()) {
    		$this->uploader = new Uploader();
     
    		if ($config) {
    			foreach ($config as $field => $attachment) {
    				if (isset($attachment['skipSave'])) {
    					$attachment['stopSave'] = $attachment['skipSave'];
    				}
     
    				$attachment = Set::merge($this->_defaults, $attachment);
    				$attachment['field'] = $field;
     
    				$columns = array($attachment['dbColumn'] => $field);
     
    				if ($attachment['transforms']) {
    					foreach ($attachment['transforms'] as $transform) {
    						$columns[$transform['dbColumn']] = $field;
    					}
    				}
     
    				$this->_attachments[$model->alias][$field] = $attachment;
    				$this->_columns[$model->alias] = $columns;
    			}
    		}
    	}
     
    	/**
    	 * Deletes any files that have been attached to this model.
    	 *
    	 * @access public
    	 * @param Model $model
    	 * @param boolean $cascade
    	 * @return mixed
    	 */
    	public function beforeDelete(Model $model, $cascade = true) {
    		if (empty($model->id)) {
    			return false;
    		}
     
    		$data = $model->read(null, $model->id);
    		$columns = $this->_columns[$model->alias];
     
    		if (!empty($data[$model->alias])) {
    			foreach ($data[$model->alias] as $column => $value) {
    				if (isset($columns[$column])) {
    					$attachment = $this->_attachments[$model->alias][$columns[$column]];
     
    					$this->uploader->setup($attachment);
    					$this->s3 = $this->s3($attachment['s3']);
     
    					$path = $attachment['saveAsFilename'] ? rtrim($attachment['uploadDir'], '/') . '/' . $value : $value;
    					$this->delete($path);
    				}
    			}
    		}
     
    		return true;
    	}
     
    	/**
    	 * Before saving the data, try uploading the image, if successful save to database.
    	 *
    	 * @access public
    	 * @param Model $model
    	 * @return mixed
    	 */
    	public function beforeSave(Model $model, $options = Array()) {
    		if (empty($model->data[$model->alias])) {
    			return true;
    		}
     
    		foreach ($model->data[$model->alias] as $field => $file) {
    			if (empty($this->_attachments[$model->alias][$field])) {
    				continue;
    			}
     
    			$attachment = $this->_attachments[$model->alias][$field];
    			$attachment = $this->callback($model, 'beforeUpload', $attachment);
    			$data = array();
     
    			// Not a form upload, so lets treat it as an import
    			if (is_string($file) && !empty($file)) {
    				$attachment['importFrom'] = $file;
    			}
     
    			// Should we continue if a file threw errors during upload?
    			if (empty($file['tmp_name']) || (isset($file['error']) && $file['error'] == UPLOAD_ERR_NO_FILE) || (is_string($file) && empty($attachment['importFrom']))) {
    				if ($attachment['stopSave'] && !$attachment['allowEmpty']) {
    					return false;
    				} else if ($attachment['allowEmpty']) {
    					if (empty($attachment['defaultPath'])) {
    						unset($model->data[$model->alias][$attachment['dbColumn']]);
    					} else {
    						$model->data[$model->alias][$attachment['dbColumn']] = $attachment['defaultPath'];
    					}
     
    					continue;
    				}
    			}
     
    			// Save model method for formatting function
    			if (!empty($attachment['name']) && method_exists($model, $attachment['name'])) {
    				$attachment['name'] = array($model, $attachment['name']);
    			}
     
    			// Setup instances
    			$this->uploader->setup($attachment);
    			$this->s3 = $this->s3($attachment['s3']);
     
    			// Upload or import the file and attach to model data
     
    			$uploadResponse = $this->upload($file, $attachment, array(
    				'overwrite' => $attachment['overwrite'],
    				'name' => $attachment['name'],
    				'append' => $attachment['append'],
    				'prepend' => $attachment['prepend']
    			));
     
    			$uploaderOptions = array(
    				'uploadDir' => $this->uploader->uploadDir,
    				'baseDir' => $this->uploader->baseDir,
    				'tempDir' => $this->uploader->tempDir
    			);
     
    			if (empty($uploadResponse)) {
    				$model->invalidate($field, __d('uploader', 'There was an error uploading this file, please try again.'));
    				return false;
    			}
     
    			$basePath = $this->transfer($uploadResponse['path']);
    			$data[$attachment['dbColumn']] = ($attachment['saveAsFilename'] && $this->s3 === null) ? basename($basePath) : $basePath;
     
    			$toDelete = array();
    			$lastPath = $basePath;
     
    			// Apply image transformations
    			if ($attachment['transforms']) {
    				foreach ($attachment['transforms'] as $options) {
    					$options['field'] = $field;
    					$options = $this->callback($model, 'beforeTransform', $options);
     
    					$method = $options['method'];
     
    					if (!method_exists($this->uploader, $method)) {
    						trigger_error(sprintf('Uploader.Attachment::beforeSave(): "%s" is not a defined transformation method.', $method), E_USER_WARNING);
    						return false;
    					}
     
    					// Apply custom options for transform
    					$this->uploader->setup($options);
     
    					// Transform image
    					$transformResponse = $this->uploader->{$method}($options);
     
    					// Rollback uploaded files if one fails
    					if (empty($transformResponse)) {
    						foreach ($data as $path) {
    							$this->delete($path);
    						}
     
    						$model->invalidate($field, __d('uploader', 'An error occured during image %s transformation.', $method));
    						return false;
    					}
     
    					// Transform successful
    					$transformPath = $this->transfer($transformResponse);
    					$data[$options['dbColumn']] = ($attachment['saveAsFilename'] && $this->s3 === null) ? basename($transformPath) : $transformPath;
     
    					// Delete original if same column name and transform name are not the same file
    					if ($options['dbColumn'] == $attachment['dbColumn'] && $lastPath != $transformPath) {
    						$toDelete[] = $lastPath;
    					}
     
    					$lastPath = $transformPath;
     
    					// Reset to default settings
    					$this->uploader->setup($uploaderOptions);
    				}
    			}
     
    			// Delete old files if replacing them
    			if ($toDelete) {
    				foreach ($toDelete as $deleteFile) {
    					$this->delete($deleteFile);
    				}
    			}
     
    			// Apply meta columns
    			if ($attachment['metaColumns']) {
    				foreach ($attachment['metaColumns'] as $field => $column) {
    					if (isset($uploadResponse[$field]) && !empty($column)) {
    						$data[$column] = $uploadResponse[$field];
    					}
    				}
    			}
     
    			// Reset S3 and delete original files
    			if ($this->s3 !== null) {
    				foreach ($this->s3->uploads as $path) {
    					$this->delete($path);
    				}
     
    				$this->s3 = null;
    			}
     
    			// Merge upload data with model data
    			$model->data[$model->alias] = $data + $model->data[$model->alias];
    		}
     
    		return true;
    	}
     
    	/**
    	 * Delete a file from Amazon S3 or locally.
    	 *
    	 * @access public
    	 * @param string $path
    	 * @return boolean
    	 */
    	public function delete($path) {
    		if ($this->s3 !== null && strpos($path, self::AS3_DOMAIN) !== false) {
    			return $this->s3->deleteObject($this->s3->bucket, $this->s3->path . basename($path));
    		}
     
    		return $this->uploader->delete($path);
    	}
     
    	/**
    	 * Return an S3 instance.
    	 *
    	 * @access public
    	 * @param array $settings
    	 * @return S3
    	 */
    	public function s3(array $settings) {
    		if (empty($settings['accessKey']) || empty($settings['secretKey'])) {
    			return null;
    		}
     
    		$ssl = isset($settings['useSsl']) ? $settings['useSsl'] : $settings['ssl'];
     
    		$s3 = new S3($settings['accessKey'], $settings['secretKey'], (bool) $ssl);
    		$s3->host = $settings['host'];
    		$s3->bucket = $settings['bucket'];
    		$s3->path = trim($settings['path'], '/');
    		$s3->format = $settings['format'];
    		$s3->uploads = array();
     
    		return $s3;
    	}
     
    	/**
    	 * Attempt to upload a file via remote import, file system import or standard upload.
    	 *
    	 * @access public
    	 * @param string|array $file
    	 * @param array $attachment
    	 * @param array $options
    	 * @return array
    	 */
    	public function upload($file, $attachment, $options) {
    		if ($attachment['importFrom']) {
    			if (preg_match('/(http|https)/', $attachment['importFrom'])) {
    				return $this->uploader->importRemote($attachment['importFrom'], $options);
     
    			} else {
    				return $this->uploader->import($attachment['importFrom'], $options);
    			}
    		}
     
    		return $this->uploader->upload($file, $options);
    	}
     
    	/**
    	 * Transfer an object to the S3 storage bucket.
    	 *
    	 * @access public
    	 * @param string $path
    	 * @return string
    	 */
    	public function transfer($path) {
    		if ($this->s3 === null) {
    			return $path;
    		}
     
    		$host = empty($this->s3->host) ? self::AS3_DOMAIN : $this->s3->host;
    		$name = basename($path);
    		$bucket = $this->s3->bucket;
     
    		if (!empty($this->s3->path)) {
    			$name = $this->s3->path . '/' . $name;
    		}
     
    		if ($this->s3->putObjectFile($this->uploader->formatPath($path), $bucket, $name, S3::ACL_PUBLIC_READ)) {
    			$this->s3->uploads[] = $path;
     
    			return String::insert($this->s3->format, array(
    				'bucket' => $bucket,
    				'path' => $name,
    				'host' => $host
    			), array(
    				'before' => '{',
    				'after' => '}'
    			));
    		}
     
    		return $path;
    	}
     
    	/**
    	 * Trigger a callback function to modify data.
    	 *
    	 * @access public
    	 * @param Model $model
    	 * @param string $method
    	 * @param array $options
    	 * @return array
    	 */
    	public function callback(Model $model, $method, array $options) {
    		if (method_exists($model, $method)) {
    			return $model->{$method}($options);
    		}
     
    		return $options;
    	}
     
    }
    merci pour votre aide

  16. #16
    Expert éminent sénior

    Homme Profil pro
    Développeur Web
    Inscrit en
    Septembre 2010
    Messages
    5 380
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Puy de Dôme (Auvergne)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Septembre 2010
    Messages : 5 380
    Points : 10 410
    Points
    10 410
    Par défaut
    Salut,

    En dehors d'un problème de configuration d'un module, les principaux problèmes que l'on trouve lors de l'upload/traitement de fichiers/images sont:

    • Fichier excédant la taille maximale de la configuration serveur "post_max_size" => upload fail, $_POST et $_FILES seront vides.
    • Fichier excédant la taille maximale de la configuration serveur "upload_max_filesize" => upload fail, mais $_POST et $_FILES sont renseignés.
    • Résolution de l'image trop grande pour pouvoir être traitée par la bibliothèque GD => traitement fail, erreur de mémoire.

    • Lors de l'upload d'un gros fichier on peut aussi être aussi limité par un timeout venant d'apache => le fichier met trop longtemps à se charger.
    • Lors d'un upload ajax d'un gros fichier on peut aussi être limité par certains serveurs "nginx" qui ont (ou avaient) par défaut une configuration "client_max_body_size" de 1Mo => limite à 1Mo.


    Pour mieux savoir ce qui se passe, tu peux essayer ce module d'upload ajax/php.

    Il permet de surpasser les configurations serveur "post_max_size", "upload_max_filesize", "timeout" et sait gérer les erreur fatales en renvoyant un message approprié par exemple lorsque les images sont de trop grande résolution pour être traitées par la bibliothèque GD.

    C'est un module autonome, donc pas spécialement conçu pour cakePHP et je connais pas les contraintes ou facilités pour intégrer du code "externe", mais même si tu ne l'utilise pas à terme, il pourrait te servir pour mieux comprendre d'où vient ton erreur. Tous les exemples fournis sont prêt à l'emploi donc il te faudra moins de cinq minutes pour poser le dossier sur ton serveur et observer les messages en retour quand tu télécharges tes fichiers.
    Concernant le traitement des images il y a des exemples (tous fonctionnels) d'upload + redimensionnement, mais aussi recadrage (crop) + upload, et recadrage + upload + redimensionnement.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Upload fichier
    Par bass17 dans le forum Général JavaScript
    Réponses: 6
    Dernier message: 17/12/2004, 17h06
  2. [web] upload fichier perl
    Par lilou0210 dans le forum Web
    Réponses: 3
    Dernier message: 04/11/2004, 09h13
  3. Réponses: 3
    Dernier message: 02/09/2004, 12h26
  4. [servlet]Upload Fichier su serveur
    Par mathk dans le forum Servlets/JSP
    Réponses: 4
    Dernier message: 21/04/2004, 11h24
  5. [Struts][Oracle]Upload fichier word dans une base
    Par Maximil ian dans le forum Struts 1
    Réponses: 7
    Dernier message: 10/02/2004, 16h52

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo