yii how to change uploaded file name - php

I want to upload a image and change the original name then save it.
Model:
public function rules()
{
return array(
array('image', 'file', 'types'=>'jpg, gif, png'),
);
}
Controller:
$model->image = CUploadedFile::getInstanceByName('image');
If i save it without any other actions it will work.
But how could i change the name of image ? I try something like below:
$model->image->name = "xxx"; //CUploadedFile.name readonly
if($model->save())
$model->images->saveAs(some_path_else.newname); //the files's new name is different from database
$model->image = "abc.jpg"; //wont save it
Is the image attribute must be an instance of CUploadedFile?
Anyone help pls

do something like this
$uploadedFile = CUploadedFile::getInstance($model, 'image');
if (!empty($uploadedFile)) {
//new name will go here
$model->image = strtotime($this->getCurrentDateTime()) . '-' .$uploadedFile;
}
//this will save the image with new name
$uploadedFile->saveAs(Yii::app()->basePath.'/../public/images/user/' . $model->image);

Thanks for your answer.
I figured it out.
CUploadedFile.name is read only , so i can't change it.
The Model need a new public attribute :
public $file;
public function rules()
{
return array(
array('file', 'file', 'types'=>'jpg, gif, png'),
array('iamge', 'length'=>'255'),
);
}
Then in the controller:
$model->file = CUploadedFile::getInstanceByName('image');
$model->file->saveAs(Yii::app()->basePath.'/../public/images/user/' . $model->image);
$model->image = $model->file->name;
It's works fine.(it's not real code)
see here

Related

How to validate image store in Controller in Laravel 5.6

in My laravel 5.6 app I have image store function in my Controller like this,
public function store(Request $request)
{
$image = new Category();
if ($request->hasFile('image')) {
$dir = 'images/';
$extension = strtolower($request->file('image')->getClientOriginalExtension()); // get image extension
$fileName = str_random() . '.' . $extension; // rename image
$request->file('image')->move($dir, $fileName);
$image->categoryimage = $fileName;
}
$image->save();
}
now I need validate before save image if saving without image (empty) and if not file format is equel to (png,jpeg,png). how can I do this?
In the first line of your function
$validatedData = $request->validate([
'image' => 'required|file|mimes:jpeg,png'
]);
//image is valid
Take a look at this: docs
You can do this:
//first you should use the Request class at the top of your file
use Illuminate\Http\Request;
public function store(Request $request)
{
$validator = $request->validate([
'image' => 'required|image'
]);
if ($validator->fails()) {
// write what you want here
}
// the rest of your code
}
The file under validation must be an image (jpeg, png, bmp, gif, or svg).

Call to a member function saveAs() on string in Yii

When i am trying to upload imgage file to projectfolder\uploaded directory i got error
Fatal error: Call to a member function saveAs() on string
My controller code is as below
public function actionStore()
{
$model = new Article;
$this->performArticleValidation($model);
$userId = Yii::app()->user->getId();
if(isset($_POST['Article'])) {
$model->attributes = $_POST['Article'];
$model->avatar = CUploadedFile::getInstance($model,'avatar');
//var_dump($model->avatar); // Outside if
if($model->save()) {
//var_dump($model->avatar); // Inside if
$path = Yii::app()->basePath . '/../uploaded';
$model->avatar->saveAs($path);
EUserFlash::setSuccessMessage('Thank you.');
$this->redirect(array('index'));
}
}
}
Model is as below
public function rules() {
return array(
array(['avatar'], 'file', 'skipOnEmpty' => false, 'types' => 'jpg, jpeg, gif, png'),
);
}
When I tried to debug $model->avatar outside if condition it gives me an array of an object as shown in below image and inside if it gives me the string.
form attribute for image upload is avatar
$model->avatar->saveAs($path);
here you are trying to call saveAs() on avatar
but somehow instead of an object avatar is a string. maybe avatar was always a string.
var_dump($model->avatar)
would produce a string.
that is what the error message shows
I forgot to pass file name in saveAs() i am just passing directory path only so image not uploaded.
public function actionStore()
{
$model = new Article;
$this->performArticleValidation($model);
$userId = Yii::app()->user->getId();
if(isset($_POST['Article'])) {
$model->attributes = $_POST['Article'];
$model->created_at = date('Y-m-d H:i:s',time());
$uploadedFile = CUploadedFile::getInstance($model, 'avatar');
$model->avatar = strtotime("now").'.'.$uploadedFile->getExtensionName();
$model->created_by = $userId;
if($model->save()) {
$path = Yii::app()->basePath.'\..\uploaded\articles';
$uploadedFile->saveAs($path.'/'.$model->avatar);
EUserFlash::setSuccessMessage('Thank you.');
$this->redirect(array('index'));
}
}
}

The image path in the database is not saved

I want to upload a photo along with a text
But the photo path is not saved inside the table, but the photo is uploaded to the directory
Controller code
namespace App\Http\Controllers;
use App\Http\Requests\singlereq;
use App\infouser;
class singleupload extends Controller
{
public function uploadform()
{
return view('singleupload.upload_form');
}
public function uploadSubmit(singlereq $request)
{
$file = $request->file('imgs');
$file->move('img', $file->getClientOriginalName());
$product = infouser::create($request->all());
return 'OK Upload successful!';
}
}
Used below code. to get the image name and set the table column (your_file) your is column name in your table.
$file = $request->file('imgs');
$file->move('img', $file->getClientOriginalName());
$input = $request->all();
$name = $file->getClientOriginalName();
$input['your_file'] = $name;
$product = infouser::create($input);
return 'OK Upload successful!';

how to assign string to a file attribute after saving the file instance?

I am trying to save my uploaded file with a new name, so I must update the file attribute again to give it the new name to avoid the mismatching between the file name in the db and the name of the real file in my directory.
But the file attribute type is file, so I'll get an error saying please upload a file every time I do this process, here is my create action code:
if(isset($_POST['Customers'])) {
$model->attributes=$_POST['Customers'];
$model->image = UploadedFile::getInstance($model, 'image');
if($model->save()){
$model->image->saveAs(getcwd()."/images/customers/CUST-".$model->id."-".$model->image);
$model->image = "CUST-".$model->id."-".$model->image;
if($model->save())
return $this->redirect(['view', 'id' => $model->id]);
}
}
Here's your solution: you need two different fields.
One field is to store the name of the file. This field will be saved into the database. This field should not be set in your rules at all, because you'll never be getting it from forms.
Another field is to receive the actual file upload. This field needs to exist in your rules as type file and also be declared in your model class as a property.
Let's assume that your customer table already has a column named image.
class Customer extends ActiveRecord
{
public $imageFile;
//...
public function rules()
{
return [
//...
[['imageFile'], 'file'],
[['imageFile'], 'required'],
//...
];
}
//...
}
Now, in your controller:
if (Yii::$app->request->isPost) {
$model->load(Yii::$app->request->post());
$model->imageFile = UploadedFile::getInstance($model, 'imageFile');
if ($model->save()) {
$model->refresh();
//set image name
$model->image = "CUST-".$model->id."-".$model->imageFile->name;
//save file
$model->imageFile->saveAs(getcwd()."/images/customers/".$model->image);
//update model with file name
$model->save();
}
}
return $this->redirect(['view', 'id' => $model->id]);
It would also be a good idea to use aliases to get your upload folder. Something like Yii::getAlias("#uploads/{$model->image}").
Saving A model after Image SaveAs call .. Should Be Like
if(isset($_POST['Customers'])) {
$model->attributes=$_POST['Customers'];
$model->image = UploadedFile::getInstance($model, 'image');
if($model->validate()){
$model->image->saveAs(getcwd()."/images/customers/CUST-".$model->id."-".$model->image);
$model->image = "CUST-".$model->id."-".$model->image;
if($model->save())
return $this->redirect(['view', 'id' => $model->id]);
}
}

Can't update image in yii project

I would like to upload an image and save the image name in database. I can create it and everything is ok, but update has problems. If i update the $model->img (image) value will be blank in db.
This is my model rules:
array('img', 'file','types'=>'jpg, gif, png, jpeg', 'allowEmpty'=>true, 'on'=>'update'),
array('title, img', 'length', 'max'=>255, 'on'=>'insert,update'),
And this is the controller:
public function actionUpdate($id)
{
$model=$this->loadModel($id);
$_SESSION['KCFINDER']['disabled'] = false;
$_SESSION['KCFINDER']['uploadURL'] = Yii::app()->baseUrl."/../images/"; // URL for the uploads folder
$_SESSION['KCFINDER']['uploadDir'] = Yii::app()->basePath."/../../images/"; // path to the uploads folder
// $this->performAjaxValidation($model);
if(isset($_POST['News']))
{
$_POST['News']['img'] = $model->img;
$model->attributes=$_POST['News'];
$model->img = $_POST['News']['img'];
$uploadedFile=CUploadedFile::getInstance($model,'img');
if($model->save()){
if(!empty($uploadedFile))
{
$uploadedFile->saveAs(Yii::app()->basePath.'/../../images/'.$model->img);
}
}
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array(
'model'=>$model,
));
}
Before the save i check $model->img and it has value.
So i think something wrong with save() in update.
$_POST['News']['img'] = $model->img;
Why you did it? You must remove this line.
$model->attributes=$_POST['News'];
$model->img = $_POST['News']['img'];

Categories