Reputation: 81
When i am uploading a image it is saved in default folder that is /web. I want to save my images in user defined folder.
Upvotes: 1
Views: 12028
Reputation: 615
The best way is using yii2 file kit. https://github.com/trntv/yii2-file-kit That more feature
Upvotes: 0
Reputation: 101
If its a user defined folder, chances are pretty good you will have to create the directory on the fly, which the UploadedFile method does not do. For Yii2 I would use the createDirectory() method in the "yii\helpers\BaseFileHelper" class. ex:
use yii\web\UploadedFile;
use yii\helpers\BaseFileHelper;
$model->uploaded_file = UploadedFile::getInstance($model, 'uploaded_file');
$unique_name = uniqid('file_');
$model->file_type = $model->uploaded_file->extension;
$model->file_name = $unique_name.'.'.$model->file_type;
$model->file_path = 'uploads/projects/'. $project_id;
BaseFileHelper::createDirectory($model->file_path);
$model->uploaded_file->saveAs($model->file_path .'/'. $model->file_name);
$model->save();
Check out createDirectory
Upvotes: 4
Reputation: 8146
\Yii::$app->basePath
corresponds to your application folder,for example \myapp\backend\
.So if you want to save it to myapp\backend\data
,save it like
$file = \yii\web\UploadedFile::getInstance($model, 'logo');
$file->saveAs(\Yii::$app->basePath . '/data/'.$file);
Upvotes: -1
Reputation: 9
if ($model->load(Yii::$app->request->post())) {
$model->password=md5($model->password);
$model->photo = UploadedFile::getInstance($model, 'photo');
if($model->validate()){
$model->photo->saveAs('uploads/' . $model->photo->baseName . '.' . $model->photo->extension);
$model->save();
return $this->redirect(['index']);
}
}
It saves my images in web/uploads folder.
Upvotes: -1
Reputation: 781
//yii 1.1 example
if($file=CUploadedFile::getInstanceByName("Shorty[avatar]"))
{
$basepath = preg_replace('~([\\\]|[\/])protected~s','',Yii::app()->basePath);
$filename = $basepath ."/images/shorty_images/" . $shorty_model->id . "/";
if(!file_exists($filename))
if(!mkdir($basepath ."/images/shorty_images/" . $shorty_model->id, 0777, true))
throw new CHttpException(404,'Directory create error!');
$status = $file->saveAs($filename . iconv("UTF-8", "ASCII//IGNORE", $file->name));
}
Yii 2: http://www.yiiframework.com/doc-2.0/yii-web-uploadedfile.html
Upvotes: 0
Reputation: 432
Something like this should do the job, if you use model/active form to submit the form (upload image). The key part is saveAs, where the first parameter can be path to file. This includes also Yii Aliases.
if (\Yii::$app->request->isPost) {
$model->load(\Yii::$app->request->getBodyParams());
$file = \yii\web\UploadedFile::getInstance($model, 'image');
$file->saveAs('path/to/file');
}
Also take a deeper look into UploadedFile class.
Upvotes: 0