Изображения не будут загружены с помощью функции cakephp-upload

Я не хочу создавать простую функцию загрузки в моем приложении cakephp 3.x. Я использовал поведение CakePHP-загрузки. На данный момент я могу сохранить все необходимые данные в базе данных, но изображение не будет загружено. Я проверил некоторые связанные статьи здесь на stackoverflow, но в основном они предназначены для cakephp 2.x, а не для версии 3.x.

Вид выглядит так:

<?php echo $this->Form->create($form, ['type' => 'file', 'id' => 'form', 'class' => 'form-horizontal', 'url' => '/storages/form/content/' . $formId]); ?>

// some other input fields

<?php echo $this->Form->input('photo', ['type' => 'file']); ?>
<?php echo $this->form->end(); ?>

Функция сохранения всех связанных с фотографиями материалов в базе данных выглядит следующим образом:

// the $array consists of this data
[
'data||1' => 'data',
'photo' => [
'tmp_name' => '/Applications/MAMP/tmp/php/phpHbVBQz',
'error' => (int) 0,
'name' => 'Screen Shot 2017-08-22 at 14.26.17.png',
'type' => 'image/png',
'size' => (int) 163117
]
]

private function addContent($array) {
$form = $this->getHighestFormId();

foreach ($array as $field => $value) {
if ($value != null) {
// create new entity
$containerContent = $this->StoragecontainerContent->newEntity();

// explode field name and container_block_element_id
$explodedField = explode("||", $field); // [0] field, [1] container_block_element_id

// remove the automatic generated _ character from the string and replace it by a whitespace
// $replacedName = str_replace("_", " ", $explodedField[0]);

// create array
$data = [
'user_id' => $this->Auth->user('id'),
'form_id' => $form->maxFormId + 1,
'storagecontainer_block_element_id' => $explodedField[1],
'identifier' => $explodedField[0],
'content' => $value
];

// patch data
$containerContent = $this->StoragecontainerContent->patchEntity($containerContent, $data);

// safe value
$this->StoragecontainerContent->save($containerContent);
}
}
}

Наконец, мой класс таблицы выглядит так:

class StoragecontainerContentTable extends Table {

/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config) {
parent::initialize($config);

$this->setTable('storagecontainer_content');
$this->setPrimaryKey('id');

$this->addBehavior('Josegonzalez/Upload.Upload', [
'photo' => [
'fields' => [
'dir' => 'photo_dir',
'size' => 'photo_size',
'type' => 'photo_type'
],
'nameCallback' => function ($data, $settings) {
return strtolower($data['name']);
},
'transformer' =>  function ($table, $entity, $data, $field, $settings) {
$extension = pathinfo($data['name'], PATHINFO_EXTENSION);

// Store the thumbnail in a temporary file
$tmp = tempnam(sys_get_temp_dir(), 'upload') . '.' . $extension;

// Use the Imagine library to DO THE THING
$size = new \Imagine\Image\Box(40, 40);
$mode = \Imagine\Image\ImageInterface::THUMBNAIL_INSET;
$imagine = new \Imagine\Gd\Imagine();

// Save that modified file to our temp file
$imagine->open($data['tmp_name'])
->thumbnail($size, $mode)
->save($tmp);

// Now return the original *and* the thumbnail
return [
$data['tmp_name'] => $data['name'],
$tmp => 'thumbnail-' . $data['name'],
];
},
'deleteCallback' => function ($path, $entity, $field, $settings) {
// When deleting the entity, both the original and the thumbnail will be removed
// when keepFilesOnDelete is set to false
return [
$path . $entity->{$field},
$path . 'thumbnail-' . $entity->{$field}
];
},
'keepFilesOnDelete' => false
]
]);
}
}

1

Решение

Вы не создаете пользовательский набор данных и не сохраняете его, на самом деле в процессе сохранения нет ничего особенного, что вам нужно делать, поэтому его нет в документации.

Все, что вам нужно сделать, это использовать настроенное имя в форме, как вы уже это делаете, и связать объект с данными запроса без каких-либо изменений, затем сохранить его, а поведение при загрузке сделает все остальное, т.е. если $array это необработанные данные запроса, передайте их напрямую patchEntity(),

2

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector