i have an ActiveForm, and i want to add a field where the user can upload their photos. the problem is that i don't have an attribute for the image in the users table and every input field in 'yii' expects a model and an attribute as follows.
我有一个ActiveForm,我想添加一个用户可以上传照片的字段。问题是,我在users表中没有图像的属性,而且在“yii”中,每个输入字段都需要一个模型和属性,如下所示。
<?= $form->field($model, 'attribute')->input($platforms) ?>
i don't want to assign the image to any record nor i want to insert in in the database, i want it to be uploaded to a specific folder.
我不想把图像分配给任何记录,也不想在数据库中插入,我想把它上传到一个特定的文件夹。
i have also checked the library kartik wrote, but also requires an attribute field.
我还检查了kartik编写的库,但也需要一个属性字段。
6 个解决方案
#1
43
Follow the official documentation
按照官方文档
https://github.com/yiisoft/yii2/blob/master/docs/guide/input-file-upload.md
https://github.com/yiisoft/yii2/blob/master/docs/guide/input-file-upload.md
Form Model
形式的模型
namespace app\models;
use yii\base\Model;
use yii\web\UploadedFile;
/**
* UploadForm is the model behind the upload form.
*/
class UploadForm extends Model
{
/**
* @var UploadedFile|Null file attribute
*/
public $file;
/**
* @return array the validation rules.
*/
public function rules()
{
return [
[['file'], 'file'],
];
}
}
?>
Form View
表格视图
<?php
use yii\widgets\ActiveForm;
$form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'file')->fileInput() ?>
<button>Submit</button>
<?php ActiveForm::end(); ?>
Controller
控制器
Now create the controller that connects form and model together:
现在创建连接表单和模型的控制器:
<?php
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->file = UploadedFile::getInstance($model, 'file');
if ($model->validate()) {
$model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension);
}
}
return $this->render('upload', ['model' => $model]);
}
}
?>
Instead of model->load(...)
we are using UploadedFile::getInstance(...)
. [[\yii\web\UploadedFile|UploadedFile]]
does not run the model validation. It only provides information about the uploaded file. Therefore, you need to run validation manually via $model->validate()
. This triggers the [[yii\validators\FileValidator|FileValidator]]
that expects a file:
我们使用的不是model->load(…),而是UploadedFile: getInstance(…)。[[[\yii\web\UploadedFile|UploadedFile]]]不运行模型验证。它只提供有关上传文件的信息。因此,您需要通过$model->validate()手动运行验证。这触发了[[yii\validator \FileValidator|FileValidator]],它期望文件:
$file instanceof UploadedFile || $file->error == UPLOAD_ERR_NO_FILE //in code framework
If validation is successful, then we're saving the file:
如果验证成功,那么我们保存文件:
$model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension);
If you're using "basic" application template then folder uploads should be created under web.
如果您正在使用“基本”应用程序模板,那么应该在web下创建文件夹上传。
That's it. Load the page and try uploading. Uplaods should end up in basic/web/uploads.
就是这样。加载页面并尝试上传。空斑应该以基本/web/上传结束。
#2
14
in your view
在你的观点
use kartik\widgets\ActiveForm;
use kartik\widgets\FileInput;
$form = ActiveForm::begin(['options' => ['enctype'=>'multipart/form-data']]); //important
echo FileInput::widget([
'name' => 'filename',
'showUpload' => false,
'buttonOptions' => ['label' => false],
'removeOptions' => ['label' => false],
'groupOptions' => ['class' => 'input-group-lg']
]);
echo Html::submitButton('Submit', ['class'=>'btn btn-primary']);
ActiveForm::end();
in your controller
在你的控制器
$file = \yii\web\UploadedFile::getInstanceByName('filename');
$file->saveAs('/your/directory/'.$file->name);
#3
6
Create a read only attribute for your model like public $image
and proceed like
为您的模型创建一个只读属性,如public $imageand继续
<?= $form->field($model, 'image')->fileInput() ?>
#4
2
I really like Yii2 Dropzone.
我非常喜欢Yii2 Dropzone。
Installation:
安装:
composer require --prefer-dist perminder-klair/yii2-dropzone "dev-master"
Usage:
用法:
<?php
echo \kato\DropZone::widget([
'options' => [
'url'=> Url::to(['resource-manager/upload']),
'paramName'=>'image',
'maxFilesize' => '10',
],
'clientEvents' => [
'complete' => "function(file){console.log(file)}",
'removedfile' => "function(file){alert(file.name + ' is removed')}"
],
]);
?>
Controller:
控制器:
public function actionUpload(){
$model = new ResourceManager();
$uploadPath = Yii::getAlias('@root') .'/uploads/';
if (isset($_FILES['image'])) {
$file = \yii\web\UploadedFile::getInstanceByName('image');
$original_name = $file->baseName;
$newFileName = \Yii::$app->security
->generateRandomString().'.'.$file->extension;
// you can write save code here before uploading.
if ($file->saveAs($uploadPath . '/' . $newFileName)) {
$model->image = $newFileName;
$model->original_name = $original_name;
if($model->save(false)){
echo \yii\helpers\Json::encode($file);
}
else{
echo \yii\helpers\Json::encode($model->getErrors());
}
}
}
else {
return $this->render('upload', [
'model' => $model,
]);
}
return false;
}
#5
0
give this code after your uploaded code
上传代码后请给出此代码
//save the path in DB..
$model->file = 'uploads/'.$imageName.'.'.$model->file->extension;
$model->save();
#6
0
If you have more than one file while uploading you must use foreach for that. And you should actual name of file in a column in table and a encrypted value of that name has to be stored to avoid duplicated in the directory.. Something like this..
如果你上传的文件不止一个,你必须使用foreach。你应该在表中的列中实际的文件名,并且必须存储该名称的加密值,以避免在目录中重复。是这样的. .
$userdocs->document_name = UploadedFile::getInstances($userdocs, 'document_name');
foreach ($userdocs->document_name as $key => $file) {
$img_name = Yii::$app->security->generateRandomString();
$file->saveAs('user/business_files/' . $img_name . '.' . $file->extension);
$images = $img_name . '.' . $file->extension;
$userdocs->actual_name = $file->name;
$userdocs->user_id = $user->id;
$userdocs->document_name = $images;
$userdocs->save(false);
$userdocs = new UserDocs();
}
Here a random string is generated and it will be assign with the name of the document, and it will be stored in the table. The UserDocs is the model name.
这里将生成一个随机字符串,并使用文档的名称进行分配,并将其存储在表中。UserDocs是模型名。
#1
43
Follow the official documentation
按照官方文档
https://github.com/yiisoft/yii2/blob/master/docs/guide/input-file-upload.md
https://github.com/yiisoft/yii2/blob/master/docs/guide/input-file-upload.md
Form Model
形式的模型
namespace app\models;
use yii\base\Model;
use yii\web\UploadedFile;
/**
* UploadForm is the model behind the upload form.
*/
class UploadForm extends Model
{
/**
* @var UploadedFile|Null file attribute
*/
public $file;
/**
* @return array the validation rules.
*/
public function rules()
{
return [
[['file'], 'file'],
];
}
}
?>
Form View
表格视图
<?php
use yii\widgets\ActiveForm;
$form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'file')->fileInput() ?>
<button>Submit</button>
<?php ActiveForm::end(); ?>
Controller
控制器
Now create the controller that connects form and model together:
现在创建连接表单和模型的控制器:
<?php
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->file = UploadedFile::getInstance($model, 'file');
if ($model->validate()) {
$model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension);
}
}
return $this->render('upload', ['model' => $model]);
}
}
?>
Instead of model->load(...)
we are using UploadedFile::getInstance(...)
. [[\yii\web\UploadedFile|UploadedFile]]
does not run the model validation. It only provides information about the uploaded file. Therefore, you need to run validation manually via $model->validate()
. This triggers the [[yii\validators\FileValidator|FileValidator]]
that expects a file:
我们使用的不是model->load(…),而是UploadedFile: getInstance(…)。[[[\yii\web\UploadedFile|UploadedFile]]]不运行模型验证。它只提供有关上传文件的信息。因此,您需要通过$model->validate()手动运行验证。这触发了[[yii\validator \FileValidator|FileValidator]],它期望文件:
$file instanceof UploadedFile || $file->error == UPLOAD_ERR_NO_FILE //in code framework
If validation is successful, then we're saving the file:
如果验证成功,那么我们保存文件:
$model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension);
If you're using "basic" application template then folder uploads should be created under web.
如果您正在使用“基本”应用程序模板,那么应该在web下创建文件夹上传。
That's it. Load the page and try uploading. Uplaods should end up in basic/web/uploads.
就是这样。加载页面并尝试上传。空斑应该以基本/web/上传结束。
#2
14
in your view
在你的观点
use kartik\widgets\ActiveForm;
use kartik\widgets\FileInput;
$form = ActiveForm::begin(['options' => ['enctype'=>'multipart/form-data']]); //important
echo FileInput::widget([
'name' => 'filename',
'showUpload' => false,
'buttonOptions' => ['label' => false],
'removeOptions' => ['label' => false],
'groupOptions' => ['class' => 'input-group-lg']
]);
echo Html::submitButton('Submit', ['class'=>'btn btn-primary']);
ActiveForm::end();
in your controller
在你的控制器
$file = \yii\web\UploadedFile::getInstanceByName('filename');
$file->saveAs('/your/directory/'.$file->name);
#3
6
Create a read only attribute for your model like public $image
and proceed like
为您的模型创建一个只读属性,如public $imageand继续
<?= $form->field($model, 'image')->fileInput() ?>
#4
2
I really like Yii2 Dropzone.
我非常喜欢Yii2 Dropzone。
Installation:
安装:
composer require --prefer-dist perminder-klair/yii2-dropzone "dev-master"
Usage:
用法:
<?php
echo \kato\DropZone::widget([
'options' => [
'url'=> Url::to(['resource-manager/upload']),
'paramName'=>'image',
'maxFilesize' => '10',
],
'clientEvents' => [
'complete' => "function(file){console.log(file)}",
'removedfile' => "function(file){alert(file.name + ' is removed')}"
],
]);
?>
Controller:
控制器:
public function actionUpload(){
$model = new ResourceManager();
$uploadPath = Yii::getAlias('@root') .'/uploads/';
if (isset($_FILES['image'])) {
$file = \yii\web\UploadedFile::getInstanceByName('image');
$original_name = $file->baseName;
$newFileName = \Yii::$app->security
->generateRandomString().'.'.$file->extension;
// you can write save code here before uploading.
if ($file->saveAs($uploadPath . '/' . $newFileName)) {
$model->image = $newFileName;
$model->original_name = $original_name;
if($model->save(false)){
echo \yii\helpers\Json::encode($file);
}
else{
echo \yii\helpers\Json::encode($model->getErrors());
}
}
}
else {
return $this->render('upload', [
'model' => $model,
]);
}
return false;
}
#5
0
give this code after your uploaded code
上传代码后请给出此代码
//save the path in DB..
$model->file = 'uploads/'.$imageName.'.'.$model->file->extension;
$model->save();
#6
0
If you have more than one file while uploading you must use foreach for that. And you should actual name of file in a column in table and a encrypted value of that name has to be stored to avoid duplicated in the directory.. Something like this..
如果你上传的文件不止一个,你必须使用foreach。你应该在表中的列中实际的文件名,并且必须存储该名称的加密值,以避免在目录中重复。是这样的. .
$userdocs->document_name = UploadedFile::getInstances($userdocs, 'document_name');
foreach ($userdocs->document_name as $key => $file) {
$img_name = Yii::$app->security->generateRandomString();
$file->saveAs('user/business_files/' . $img_name . '.' . $file->extension);
$images = $img_name . '.' . $file->extension;
$userdocs->actual_name = $file->name;
$userdocs->user_id = $user->id;
$userdocs->document_name = $images;
$userdocs->save(false);
$userdocs = new UserDocs();
}
Here a random string is generated and it will be assign with the name of the document, and it will be stored in the table. The UserDocs is the model name.
这里将生成一个随机字符串,并使用文档的名称进行分配,并将其存储在表中。UserDocs是模型名。