我们如何在文件夹 yii2 框架中保存图像? [英] How we can save a image in a folder yii2 framework?

查看:34
本文介绍了我们如何在文件夹 yii2 框架中保存图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我上传图片时,它会保存在默认文件夹/web 中.我想将我的图像保存在用户定义的文件夹中.

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.

推荐答案

如果它是用户定义的文件夹,很有可能您必须动态创建目录,UploadedFile 方法不行.对于 Yii2,我将使用yii\helpers\BaseFileHelper"类中的 createDirectory() 方法.例如:

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();

查看createDirectory

这篇关于我们如何在文件夹 yii2 框架中保存图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆