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

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'));
}
}
}

Related

Pass the value from a Controller to the view

I created a form and passed the values for name and picture from the form. The value is accessed from the Upload controller as follows:
$data = array(
'title' => $this->input->post('title', true),
'name' => $this->input->post('name',true),
'picture' => $this->file_upload($_FILES['picture'])
);
return $data;
I need to pass these values to the view so, I modified the above code as:
class Upload extends CI_Controller
{
function __construct() {
parent::__construct();
}
public function input_values(){
$data = array(
'name' => $this->input->post('name',true),
'picture' => $this->file_upload($_FILES['picture'])
);
$this->load->view('documents', $data); }
function add(){
$data = $this->input_values();
if($this->input->post('userSubmit')) {
$this->file_upload(($_FILES['picture']));
if (!empty($_FILES['picture']['name'])) {
$config['upload_path'] = 'uploads/docs/';
$config['allowed_types'] = 'jpg|jpeg|png|gif|pdf|docx';
$config['file_name'] = $_FILES['picture']['name'];
$data['picture']=$this->file_upload($_FILES['picture']);
}
}
return $this->db->insert('files', $data);
}
//logo image upload
public function file_upload($file)
{
$this->my_upload->upload($file);
if ($this->my_upload->uploaded == true) {
$this->my_upload->file_new_name_body = 'file_' . uniqid();
$this->my_upload->process('./uploads/docs/');
$image_path = "uploads/docs/" . $this->my_upload->file_dst_name;
return $image_path;
} else {
return null;
}
}
}
But I am able to get only the value of title. Following error occurs for both name and title:
Message: Undefined variable: name
I have accessed the variables from the view as follows:
<?php var_dump($title)?>
<?php var_dump($name)?
<?php var_dump($picture)?>
so, this part is where you get the post data and load view (contain the upload form)
public function input_values() {
$data = array(
'name' => $this->input->post('name',true),
'picture' => $this->file_upload($_FILES['picture'])
);
$this->load->view('documents', $data);
}
then this part is handle the post request from the upload form:
function add() {
$data = $this->input_values();
if($this->input->post('userSubmit')) {
$this->file_upload(($_FILES['picture']));
if (!empty($_FILES['picture']['name'])) {
$config['upload_path'] = 'uploads/docs/';
$config['allowed_types'] = 'jpg|jpeg|png|gif|pdf|docx';
$config['file_name'] = $_FILES['picture']['name'];
$data['picture']=$this->file_upload($_FILES['picture']);
}
}
return $this->db->insert('files', $data);
}
and this part is where you upload the file
public function file_upload($file)
{
$this->my_upload->upload($file);
if ($this->my_upload->uploaded == true) {
$this->my_upload->file_new_name_body = 'file_' . uniqid();
$this->my_upload->process('./uploads/docs/');
$image_path = "uploads/docs/" . $this->my_upload->file_dst_name;
return $image_path;
} else {
return null;
}
}
when you call add() function, it call input_values() function then load views then the next line of codes won't be executed (cmiiw).
so, maybe you want to change with this :
public function index() {
if ($this->input->post()) {
// then handle the post data and files tobe upload here
// save the post data to $data, so you will able to display them in view
} else {
// set the default data for the form
// or just an empty array()
$data = array();
}
// if the request was not a post, render view that contain form to upload file
$this->load->view('nameOfTheView', $data);
}

How to upload Image in Database in Laravel 5.7?

I'm making an app in Laravel 5.7 . I want to upload image in database through it and I want to show it from database.
I have tried different methods around the Internet as I was getting issues in
Intervention\Image\Facades\Image
I followed many advices from Internet make changes in config.app
made changes in Composer
At the end used
use Intervention\Image\Facades\Image as Image;
So I get resolved from issue "Undefined class Image"
but now I' m getting issues as "Undefined class File",
Method getClientOriginalExtension not found.
Method Upsize, make not found.
My code is
<?php
namespace App\Http\Controllers;
use File;
use Intervention\Image\Facades\Image as Image;
use App\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
//
protected $user;
/**
* [__construct description]
* #param Photo $photo [description]
*/
public function __construct(
User $user )
{
$this->user = $user;
}
/**
* Display photo input and recent images
* #return view [description]
*/
public function index()
{
$users = User::all();
return view('profile', compact('users'));
}
public function uploadImage(Request $request)
{
$request->validate([
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
//check if image exist
if ($request->hasFile('image')) {
$images = $request->file('image');
//setting flag for condition
$org_img = $thm_img = true;
// create new directory for uploading image if doesn't exist
if( ! File::exists('images/originals/')) {
$org_img = File::makeDirectory('images/originals/', 0777, true);
}
if ( ! File::exists('images/thumbnails/')) {
$thm_img = File::makeDirectory('images/thumbnails', 0777, true);
}
// loop through each image to save and upload
foreach($images as $key => $image) {
//create new instance of Photo class
$newPhoto = new $this->user;
//get file name of image and concatenate with 4 random integer for unique
$filename = rand(1111,9999).time().'.'.$image->getClientOriginalExtension();
//path of image for upload
$org_path = 'images/originals/' . $filename;
$thm_path = 'images/thumbnails/' . $filename;
$newPhoto->image = 'images/originals/'.$filename;
$newPhoto->thumbnail = 'images/thumbnails/'.$filename;
//don't upload file when unable to save name to database
if ( ! $newPhoto->save()) {
return false;
}
// upload image to server
if (($org_img && $thm_img) == true) {
Image::make($image)->fit(900, 500, function ($constraint) {
$constraint->upsize();
})->save($org_path);
Image::make($image)->fit(270, 160, function ($constraint) {
$constraint->upsize();
})->save($thm_path);
}
}
}
return redirect()->action('UserController#index');
}
}
Please suggest me any Image Upload code without updating repositories or suggest me how can I remove issues from this code.
The beginning of time read below link because laravel handled create directory and hash image and put directory
laravel file system
then read file name when stored on directory and holds name on table field when need image retrieve name field and call physical address on server
$upload_id = $request->file('FILENAME');
$file_name = time().$upload_id->getClientOriginalName();
$destination =
$_SERVER["DOCUMENT_ROOT"].'/adminbusinessplus/storage/uploads';
$request->file('FILENAME')->move($destination, $file_name);
$string="123456stringsawexs";
$extension = pathinfo($upload_id, PATHINFO_EXTENSION);
$path = $destination.'/'.$file_name;
$public =1;
$user_id = $request->logedin_user_id;
$hash = str_shuffle($string);
$request->user_id = $request->logedin_user_id;
$request->name = $file_name;
$request->extension = $extension;
$request->path = $path;
$request->public = $public;
$request->hash = $hash;
//$request INSERT INTO MODEL uploads
$file_id = Module::insert("uploads", $request);

Call to a member function saveAs() on a non-object in yii2 file upload

I am using kartik fileUpload extension for uploading of files in yii2, As soon as i select a file and submit, im getting
Call to a member function saveAs() on a non-object
I have checked other post regarding this issue but its not helping,
My View code..
<?php echo $form->field($documents, 'sars_certificate')->label(false)->
widget(FileInput::classname(), [
'pluginOptions' => [
'showCaption' => true,'showRemove' => true,'showClose' => true,
'showPreview' => true,'uploadAsync' => true,
'showUpload' => false,'maxFileSize'=> 2000,'autoReplace'=> true,
'placeholder' => 'Select a File...',],]); ?>
My model code..
[['sars_certificate'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg,pdf,jpeg']
And My controller code..
public function actionCreate()
{
$model = new Projects();
$documents = new ProjectDocuments();
$borrower_id = Yii::$app->user->identity->id;
$code = $model->accessCode(10);
if ($model->load(Yii::$app->request->post()))
{
//All $model related things will bw done
//In this im doing file upload
$documents->borrower_id = $borrower_id;
$documents->project_id = $code;
$documents->save(false);
$documents->sars_certificate = UploadedFile::getInstances($documents,'sars_certificate');
$documents->sars_certificate->saveAs('user/purchase_order/' . $documents->sars_certificate->baseName . '.' . $documents->sars_certificate->extension);
$documents->sars_certificate = $documents->sars_certificate;
$documents->save(false);
return $this->redirect(['index']);
}
I have given if($documents->validate()){ **** }. But its not coming under if condition itself, so i removed it. Now it says above error..
Please anyone help in this, im wasting lot of time on this...
1) To avoid duplicate images, append time() in image name.
2) Remove $documents->save(false); before UploadInstance.
public function actionCreate() {
$model = new Projects();
$documents = new ProjectDocuments();
$borrower_id = Yii::$app->user->identity->id;
$code = $model->accessCode(10);
if ($model->load(Yii::$app->request->post())) {
//All $model related things will bw done
//In this im doing file upload
$documents->borrower_id = $borrower_id;
$documents->project_id = $code;
if(UploadedFile::getInstance($documents, 'sars_certificate')){
$image = UploadedFile::getInstance($documents, 'sars_certificate');
$imageName = time().$image->name;
$path = "user/purchase_order/".$imageName;
if($image->saveAs($path)){
$documents->sars_certificate = $imageName;
}
}
$documents->save(false);
return $this->redirect(['index']);
}
}
Update
public function actionCreate() {
$model = new Projects();
$documents = new ProjectDocuments();
$borrower_id = Yii::$app->user->identity->id;
$code = $model->accessCode(10);
if ($model->load(Yii::$app->request->post())) {
//All $model related things will bw done
//In this im doing file upload
$documents->borrower_id = $borrower_id;
$documents->project_id = $code;
if(UploadedFile::getInstance($documents, 'sars_certificate')){
$image = UploadedFile::getInstance($documents, 'sars_certificate');
if($image){
$imageName = time().$image->name;
$path = "user/purchase_order/".$imageName;
if($image->saveAs($path)){
$documents->sars_certificate = $imageName;
}
}
}
$documents->save(false);
return $this->redirect(['index']);
}
}

Yii2: Call to a member function saveAs() on null while uploading multiple file

While uploading multiple file getting this error:
When I put [['file'], 'file', 'maxFiles' => 4],in model getting following error:
Call to a member function saveAs() on null
But when I put this [['file'], 'file'], in model, its uploading.
Why am I getting error?
View:
<?php echo $form->field($model,'file[]')->label(false)->widget(FileInput::classname(),
[
'options'=>['accept'=>'image/*', 'multiple'=>true],
'pluginOptions'=>['allowedFileExtensions'=>['jpg','gif','png']
]]);
?>
Controller:
public function actionCreate()
{
$model = new RoomTypes();
if ($model->load(Yii::$app->request->post()))
{
$imageName = $model->room_type;
$model->file = UploadedFile::getInstance($model, 'file');
$model->file->saveAs( 'uploads/room_img/'.$imageName.'.'.$model->file->extension);
//save the path in the db column
$model->images = 'uploads/room_img/'.$imageName.'.'.$model->file->extension;
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
}
else
{
return $this->render('create', [
'model' => $model,
]);
}
}
Use getInstances instead of getInstance as according to their respective documentations, the first returns all uploaded files for a given model attribute while the second is designed to return a single one.
Then loop and save them one by one :
if ($model->load(Yii::$app->request->post())) {
$imageName = $model->room_type;
$model->imageFiles = UploadedFile::getInstances($model, 'imageFiles');
$all_files_paths = [];
foreach ($model->imageFiles as $file_instance) {
// this should hold the new path to which your file will be saved
$path = 'uploads/room_img/' . $file_instance->baseName . '.' . $file_instance->extension;
// saveAs() method will simply copy the file
// from its temporary folder (C:\xampp\tmp\php29C.tmp)
// to the new one ($path) then will delete the Temp File
$file_instance->saveAs($path);
// here the file should already exist where specified within $path and
// deleted from C:\xampp\tmp\ just save $path content somewhere or in case you need $model to be
// saved first to have a valid Primary Key to maybe use it to assign
// related models then just hold the $path content in an array or equivalent :
$all_files_pathes []= $path;
}
$model->save();
/*
after $model is saved there should be a valid $model->id or $model->primaryKey
you can do here more stuffs like :
foreach($all_files_pathes as $path) {
$image = new Image();
$image->room_id = $model->id;
$image->path = $path;
$image->save();
}
*/
return $this->redirect(['view', 'id' => $model->id]);
}
See docs for more info.

yii how to change uploaded file name

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

Categories