我正在使用3.4 cakephp版本,但文件已成功上传,但我希望在请求实体中更新网址。我可以更新一个实体但不是全部: $ post-> url = WWW_ROOT。' uploads / filename';
Html表格:
<?= $this->Form->create(null, ['class' => 'form-horizontal', 'id' => 'postSubmit', 'type' => 'file', 'autocomplete' => 'off'])?>
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 control-label">Ad Category:</label>
<div class="col-sm-8">
<?= $this->Form->select('category_id', $categories, ['class' => 'form-control required categorySelected', 'empty' => 'Select Category'])?>
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-4 control-label">Photos(5 max):</label>
<div class="col-sm-8">
<?= $this->Form->input('images.', [ 'type' => 'file', 'id' => 'image', 'multiple' => 'multiple', 'accept' => 'image/jpg, image/jpeg', 'label' => false])?>
<p class="help-block">Good photos quick response</p>
</div>
</div>
<div class="form-group">
<div class="col-sm-8 col-sm-offset-4">
<?= $this->Form->button('Post Now', ['class' => 'btn custom_btn btn-sm', 'type' => 'submit', 'label' => false])?>
</div>
</div>
</form>
控制器操作:
$post = $this->Posts->newEntity();
$post = $this->Posts->patchEntity($post, $this->request->getData());
if($this->request->getData()['images']) {
$dir = new Folder(WWW_ROOT.'uploads', true, 0755);
$files = $this->request->getData()['images'];
foreach ($files as $key => $file) {
if($file['error'] == 0) {
$info = pathinfo($file["name"]);
$newfilename = $info["filename"].'_'.time() . '.'. $info["extension"];
if(move_uploaded_file($file["tmp_name"], WWW_ROOT.'uploads/' . $newfilename)) {
$post->url = WWW_ROOT.'uploads/' . $newfilename;
}
}
}
}
if ($this->Posts->save($post)) {
$this->Flash->success('Post has been submitted successfully. Please wait
for approval');
}
答案 0 :(得分:0)
我建议您实施{{3>}描述的 bellow :
上传多个相关图片
此示例将向您展示如何上传与当前表类相关的许多图像。示例设置可能是您有Users表类和UserImages表类。以下示例仅为CakePHP3-Proffer。
<强>表格强>
关系设置如下。请务必将行为附加到正在接收上载的表类。
// src/Model/Table/UsersTable.php
$this->hasMany('UserImages', ['foreignKey' => 'user_id'])
// src/Model/Table/UserImagesTable.php
$this->addBehavior('Proffer.Proffer', [
'image' => [
'dir' => 'image_dir',
'thumbnailSizes' => [
'square' => ['w' => 100, 'h' => 100],
'large' => ['w' => 250, 'h' => 250]
]
]
]);
$this->belongsTo('Users', ['foreignKey' => 'user_id', 'joinType' => 'INNER']);
<强>实体强>
您的实体必须在其$_accessible
数组中允许相关字段。因此,在我们的示例中,我们需要检查'user_images' => true
是否包含在我们的用户实体中。
<强>控制器强>
不需要对标准控制器代码进行任何更改,因为Cake会默认自动保存任何第一级关联数据。由于我们的用户表与我们的UserImages表直接相关,因此我们无需进行任何更改。
如果您正在使用相关模型数据,则需要使用'associated'
键指定在baked code时填充的关联。
<强>模板强>
您需要使用正确的字段名称在模板中包含相关字段,以便正确格式化您的请求数据。
// Don't forget that you need to include ['type' => 'file'] in your ->create() call
<fieldset>
<legend>User images</legend>
<?php
echo $this->Form->input('user_images.0.image', ['type' => 'file']);
echo $this->Form->input('user_images.1.image', ['type' => 'file']);
echo $this->Form->input('user_images.2.image', ['type' => 'file']);
?>
</fieldset>
如何处理现有图像的显示,删除现有图像以及添加新的上传字段取决于您,并且超出了本示例的范围。