I am using Yii framework and I want to create user registration page. Everything seems to work fine but when i want to upload user image, I get an error message:
include(Self.php) [<a href='function.include'>function.include</a>]: failed to open stream: No such file or directory
Here is my SiteController code:
public function actionRegister()
{
$model=new RegisterForm;
// uncomment the following code to enable ajax-based validation
if(isset($_POST['ajax']) && $_POST['ajax']==='register-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
if(isset($_POST['RegisterForm']))
{
$model->attributes=$_POST['RegisterForm'];
if($model->validate())
{
$user = new User;
$user->username = $_POST['RegisterForm']['username'];
$password = $_POST['RegisterForm']['password'];
$salt = Security::GenerateSalt(128);
$user->password = hash('sha512', $password.$salt);
$user->question = $_POST['RegisterForm']['question'];
$user->answer = $_POST['RegisterForm']['answer'];
$user->salt = $salt;
$user->email = $_POST['RegisterForm']['email'];
$user->fullname = $_POST['RegisterForm']['fullname'];
$user->birth = $_POST['RegisterForm']['birth'];
$user->avatar = CUploadedFile::getInstance($model,'image');
$user->avatar->saveAs('/images/users.test.jpg');
$user->about = $_POST['RegisterForm']['about'];
$user->signup = date('d/m/y');
$user->login = date('d/m/y');
$user->save();
}
}
$this->render('register',array('model'=>$model));
}
Here is my RegisterForm model code:
<?php
class RegisterForm extends CFormModel
{
[.....]
public $avatar;
[.....]
public function rules()
{
return array(
[......]
array('avatar', 'file',
'types'=>'jpg, gif, png',
'maxSize'=>1024 * 1024 * 2,
'tooLarge'=>'The file was larger than 2MB. Please upload a smaller file.',
'wrongType'=>'Please upload only images in the format jpg, gif, png',
'tooMany'=>'You can upload only 1 avatar',
'on'=>'upload'),
[......]
}
The view:
<div class="row">
<?php echo $form->labelEx($model,'avatar'); ?>
<?php echo CHtml::activeFileField($model, 'avatar'); ?>
<?php echo $form->error($model,'avatar'); ?>
</div>
Might be a directory permission problem. To be sure if it is, do a
chmod 0777 <dir_name>
Once you are sure, you can reset the permissions properly.
Related
Hi im trying to upload an image but the image is not getting uploaded to the folder.
and i donĀ“t get any error message is there anyone that have a solution to this i followed the documentation on https://www.yiiframework.com/doc/guide/2.0/en/input-file-upload
Controller
public function actionUpload()
{
$model = new UploadForm();
if (Yii::$app->request->isPost) {
$model->imageFile = Uploadedfile::getInstance($model, 'imagefile');
if ($model->upload()) {
return;
}
}
return $this->render('upload', ['model' => $model]);
}
Model
public $imageFile;
public $hight;
public $width;
public function rules()
{
return [
[['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg, gif'],
];
}
public function upload()
{
if ($this->validate()) {
$path = $this->uploadPath() . $this->imageFile->namespace . '.' . $this->imageFile->extension;
$this->imageFile->saveAs($path);
$this->image = $this->imageFile->basename . '.' . $this->imageFile->extension;
return true;
} else {
return false;
}
}
public function uploadPath(){
return 'basic/web/uploads/';
}
View
<div class="col-lg-4">
<h2>Heading</h2>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
<?= $form->field($model, 'imageFile')->fileInput() ?>
<button>Resize</button>
<?php ActiveForm::end() ?>
</div>
I think file was not saved to basic/web/uploads folder, please do according to ex, $this->imageFile->saveAs('uploads/' ...
Also try create folder 'uploads' in web/, after this check permissions to the folder
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);
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'));
}
}
}
I am new in codeigniter. And i was trying to upload images for a product. Right now i am trying with uploading only one image for each product. And i have done this in my controller:
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Users extends CI_Controller
{
function __construct() {
parent::__construct();
$this->load->model('user');
}
function add(){
if($this->input->post('userSubmit')){
//Check whether user upload picture
if(!empty($_FILES['picture']['name'])){
$config['upload_path'] = 'uploads/images/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['picture']['name'];
//Load upload library and initialize configuration
$this->load->library('upload',$config);
$this->upload->initialize($config);
if($this->upload->do_upload('picture')){
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
}else{
$picture = '';
}
}else{
$picture = '';
}
//Prepare array of user data
$userData = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'picture' => $picture
);
//Pass user data to model
$insertUserData = $this->user->insert($userData);
//Storing insertion status message.
if($insertUserData){
$this->session->set_flashdata('success_msg', 'User data have been added successfully.');
}else{
$this->session->set_flashdata('error_msg', 'Some problems occured, please try again.');
}
}
//Form for adding user data
$data['data']=$this->user->getdata();
$this->load->view('show',$data);
}
public function show()
{
#code
$data['data']=$this->user->getdata();
$this->load->view('show',$data);
}
}
I have this in my model:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Model{
function __construct() {
$this->load->database();
$this->tableName = 'users';
$this->primaryKey = 'id';
}
public function insert($data = array()){
if(!array_key_exists("created",$data)){
$data['created'] = date("Y-m-d H:i:s");
}
if(!array_key_exists("modified",$data)){
$data['modified'] = date("Y-m-d H:i:s");
}
$insert = $this->db->insert($this->tableName,$data);
if($insert){
return $this->db->insert_id();
}else{
return false;
}
}
public function getdata()
{
$query=$this->db->get('users');
return $query->result_array();
}
}
Issue is i am being able to store data along with image name in the database, and the selected image is uploaded in the specified folder in project folder which currently is:
root folder->image:
-application
-system
-uploads
.images(images are saved here)
Now in the problem is with view. I am trying to access the stored images dynamically like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>show</title>
</head>
<body>
<table border='1' cellpadding='4'>
<tr>
<td><strong>User_Id</strong></td>
<td><strong>Name</strong></td>
<td><strong>Image</strong></td>
<td><strong>Option</strong></td>
</tr>
<?php foreach ($data as $p): ?>
<tr>
<td><?php echo $p['id']; ?></td>
<td><?php echo $p['name']; ?></td>
<td><img src="../uploads/images/<?php echo $p['picture']; ?>" /> </td>
<td>
View |
</td>
</tr>
<?php endforeach; ?>
</table>
With this image source the image is not coming. only imge crack thumbnails is seen. I also tried giving root folder of image manually like this:
<img src="../uploads/images/image-0-02-03-15420e726f6e9c97408cbb86b222586f7efe3b002e588ae6bdcfc3bc1ea1561e-V.jpg" />
or like this
<img src="../../uploadsimages/image-0-02-03-15420e726f6e9c97408cbb86b222586f7efe3b002e588ae6bdcfc3bc1ea1561e-V.jpg" />
but it ain't helping. Can anyone help me? Any suggestions and advice are highly welcome.Thank you.
try this
<img src="<?php echo base_url('uploads/images/'.$p['picture']); ?>"/>
insted of this line
<img src="../uploads/images/<?php echo $p['picture']; ?>" />
also set your folder location corectly
Just a silly mistake. I made my virtual host to point up to index.html of root folder. so just pointing up to root folder the problem was solved.
I've been searching all around the net to try to fix this problem. Changed the code in my controllersfolder multiple times and still no solution. I changed the permissions of my img folder and products folder to 777 and still no success.
This is the structure of my folders on my FTP cyberduck:
-->app_base/ ( Has Everything from the base laravel folder EXCEPT the /public/ folder)
-->[some other folders...]
-->public_html/
-->daveswebapp.us/ (name of my website. Has all the content of my base public/folder)
-->img
-->products
[empty folder]
This is the error I receive each time I try to upload new product images in my admin panel:
Intervention \ Image \ Exception \ NotWritableException
Can't write image data to path (/home2/ecuanaso/app_base/bootstrap/img/products/1417822656.jpg)
PRODUCTS CONTROLLER CODE:
<?php
class ProductsController extends BaseController {
public function __construct() {
parent::__construct();
$this->beforeFilter('csrf', array('on'=>'post'));
$this->beforeFilter('admin');
}
public function getIndex() {
$categories = array();
foreach(Category::all() as $category) {
$categories[$category->id] = $category->name;
}
return View::make('products.index')
->with('products', Product::all())
->with('categories', $categories);
}
public function postCreate() {
$validator = Validator::make(Input::all(), Product::$rules);
if ($validator->passes()) {
$product = new Product;
$product->category_id = Input::get('category_id');
$product->title = Input::get('title');
$product->description = Input::get('description');
$product->price = Input::get('price');
$image = Input::file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$path = public_path('img/products/' . $filename);
Image::make($image->getRealPath())->resize(468, 249)->save($path);
$product->image = 'img/products/'.$filename;
$product->save();
return Redirect::to('admin/products/index')
->with('message', 'Product Created');
}
return Redirect::to('admin/products/index')
->with('message', 'Something went wrong')
->withErrors($validator)
->withInput();
}
public function postDestroy() {
$product = Product::find(Input::get('id'));
if ($product) {
File::delete('public/'.$product->image);
$product->delete();
return Redirect::to('admin/products/index')
->with('message', 'Product Deleted');
}
return Redirect::to('admin/products/index')
->with('message', 'Something went wrong, please try again');
}
public function postToggleAvailability() {
$product = Product::find(Input::get('id'));
if ($product) {
$product->availability = Input::get('availability');
$product->save();
return Redirect::to('admin/products/index')->with('message', 'Product Updated');
}
return Redirect::to('admin/products/index')->with('message', 'Invalid Product');
}
}
Images should go into public folder and not in app directory in your code you are trying to move the image into app directoy but defining directory address with public_path the following code uploads an image into your public/uploads folder which is then accessible via visiting yourdomain.com/img.jpg
//create two empty variables outside of conditional statement because we gonna access them later on
$filename = "";
$extension = "";
//check if you get a file from input, assuming that the input box is named photo
if (Input::hasFile('photo'))
{
//create an array with allowed extensions
$allowedext = array("png","jpg","jpeg","gif");
/get the file uploaded by user
$photo = Input::file('photo');
//set the destination path assuming that you have chmod 777 the upoads folder under public directory
$destinationPath = public_path().'/uploads';
//generate a random filename
$filename = str_random(12);
//get the extension of file uploaded by user
$extension = $photo->getClientOriginalExtension();
//validate if the uploaded file extension is allowed by us in the $allowedext array
if(in_array($extension, $allowedext ))
{
//everything turns to be true move the file to the destination folder
$upload_success = Input::file('photo')->move($destinationPath, $filename.'.'.$extension);
}
Not sure if a a solution goes here but I figured it out after days of seaching.
I was saving the file into the wrong directory. took out the public from ->save method
I changed
Image::make($image->getRealPath())->resize(468, 249)->save('public/img/products/'.$filename);
to:
Image::make($image->getRealPath())->resize(468, 249)->save('img/products/'.$filename);