gpt4 book ai didi

image - 使用验证器设置图像最大文件大小

转载 作者:行者123 更新时间:2023-12-02 06:33:02 27 4
gpt4 key购买 nike

我正在使用文件输入小部件在 Yii2 中实现图像上传,如 http://demos.krajee.com/widget-details/fileinput 所示.我可以知道如何设置上传的文件大小限制吗?

我已经添加了:

['image', 'file', 'extensions' => ['png', 'jpg', 'gif'], 'maxSize' => 1024 * 1024 * 1024],

模型内部 rules()但它似乎不起作用。

希望有人能指教。谢谢。

在 View 中:
<?php $form = ActiveForm::begin(['enableClientValidation' => false,  'options' => [ 'enctype' => 'multipart/form-data']]); ?>


<?php

echo $form->field($model, 'image')->widget(FileInput::classname(), [
'options'=>['accept'=>'image/*', 'multiple'=>true],
'pluginOptions'=>['allowedFileExtensions'=>['jpg', 'jpeg', 'gif','png']]
]);

?>

<?php ActiveForm::end(); ?>

在 Controller 中:
    $model = new IMAGEMODEL();  

Yii::$app->params['uploadPath'] = Yii::$app->basePath . '/web/uploads/PROJECT/';


if ($model->load(Yii::$app->request->post())) {
// get the uploaded file instance. for multiple file uploads
// the following data will return an array
$image = UploadedFile::getInstance($model, 'image');


// store the source file name
$model->FILENAME = $image->name;
$ext = end((explode(".", $image->name)));

// generate a unique file name

$model->AVATAR = Yii::$app->security->generateRandomString().".{$ext}";
$model->STD_ID=$_POST['IMAGEMODEL']['STD_ID'];


// the path to save file, you can set an uploadPath
// in Yii::$app->params (as used in example below)
$path = Yii::$app->params['uploadPath'] . $model->AVATAR;

if($model->save()){
$image->saveAs($path);
Yii::$app->session->setFlash('success', 'Image uploaded successfully');
return $this->redirect(['view', 'id'=>$id]);

} else {
Yii::$app->session->setFlash('error', 'Fail to save image');
}
}

在模型中:
public function rules()
{
return [
[['STD_ID', 'FILENAME'], 'required'],
[['FILENAME'], 'string'],
[['LAST_UPD_ON'], 'safe'],
[['STD_ID'], 'string', 'max' => 50],
[['LAST_UPDATE_BY'], 'string', 'max' => 150],

[['image', 'FILENAME'], 'safe'],
['image', 'file', 'extensions' => ['png', 'jpg', 'gif'], 'maxSize' => 1024 * 1024 * 1],

];
}

最佳答案

1) maxSize参数需要字节数。在您的示例中,您设置了 1 Gb。对于 2 Mb,它应该是:

['image', 'file', 'extensions' => ['png', 'jpg', 'gif'], 'maxSize' => 1024 * 1024 * 2],

2) 另请检查 upload_max_filesize INI 设置。

3) 确保通过 yii\web\UploadedFile 的实例调用 getInstance()验证之前的方法(对于多个文件使用 getInstances() ):
$this->image = UploadedFile::getInstance($this, 'image');

关于image - 使用验证器设置图像最大文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28312227/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com