我想在我的db中保存多个图像(最多5个),我该怎么做? 为了保存图像,我有这个输入:
?= $form->field($Form, 'images[]')->fileInput(['multiple' => true, 'accept' => 'image/*','id'=>'gallery-photo-add'])->label(false) ?>
在我的模型中,我有必须保存的5个图像的图像和字段; 但是当我想要获得这样的图像时:
$Form->image1 = $this->images[0];
这个在我的数据库中是空的。 也许问题是大量保存在$ _FILES? 我的要求是什么:
$_FILES
Name Value
Form [
'name' => [
'images' => [
0 => 'weight.png'
]
]
'type' => [
'images' => [
0 => 'image/png'
]
]
'tmp_name' => [
'images' => [
0 => 'W:\\XAMPP\\tmp\\php3FD3.tmp'
]
]
'error' => [
'images' => [
0 => 0
]
]
'size' => [
'images' => [
0 => 500
]
]
]
答案 0 :(得分:0)
要保存多张图片,您应该使用Yii2的UploadedFile类。 例如,您希望在数据库中保存多个图像。您的控制器代码类似于:
namespace app\controllers;
use Yii;
use yii\web\Controller;
use app\models\UploadForm;
use yii\web\UploadedFile;
class SiteController extends Controller
{
public function actionUpload()
{
$model = new UploadForm();
if (Yii::$app->request->isPost) {
$model->imageFiles = UploadedFile::getInstances($model, 'imageFiles');
if ($model->upload()) {
// file is uploaded successfully
return;
}
}
return $this->render('upload', ['model' => $model]);
}
}
这是型号:
namespace app\models;
use yii\base\Model;
use yii\web\UploadedFile;
class UploadForm extends Model
{
/**
* @var UploadedFile[]
*/
public $imageFiles;
public function rules()
{
return [
[['imageFiles'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg', 'maxFiles' => 4],
];
}
public function upload()
{
if ($this->validate()) {
foreach ($this->imageFiles as $file) {
$file->saveAs('uploads/' . $file->baseName . '.' . $file->extension);
}
return true;
} else {
return false;
}
}
}
在您的上传功能中,您可以将图像保存到数据库或将其保存在文件夹中,并将图像的路径写入表格中的相应字段。