问题
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.
回答1:
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
回答2:
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.
回答3:
//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
回答4:
The best way is using yii2 file kit. https://github.com/trntv/yii2-file-kit That more feature
- File upload widget (based on Blueimp File Upload)
- Component for storing files (built on top of flysystem)
- Actions to download, delete, and view (download) files
- Behavior for saving files in the model and delete files when you delete a model
回答5:
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.
回答6:
\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);
来源:https://stackoverflow.com/questions/24422769/how-we-can-save-a-image-in-a-folder-yii2-framework