I tried so many time but this code is not working. I don't know why. It is a image upload form. This code worked for another form but here it's getting an error: Call to a member function isValid() on a non-object
$file = array('dest_img' => Input::file('dest_img'));
// checking file is valid.
if (Input::file('dest_img')->isValid()) {
$destinationPath = 'uploads'; // upload path
$extension = Input::file('dest_img')->getClientOriginalExtension(); // getting image extension
$fileName = $s.'.'.$extension;
$imgPath= $destinationPath.'/'.$fileName;
//return $imgPath;
// renameing image
Input::file('dest_img')->move($destinationPath, $fileName); // uploading file to given path
// sending back with message
//Session::flash('success', 'Upload successfully');
//return Redirect::to('tblaze_admin/bannerAdd');
$data=array(
'dest_title' =>$input['dest_title'],
'dest_desc' =>$input['dest_desc'],
'dest_img' =>$imgPath,
);
//$result=Cms::where('cms_id',$cms_id)->update($data);
$result=Destination::where('dest_id',$dest_id)->update($data);
if($result >0)
{
\Session::flash('flash_message','Destination Updated Successfull!!');
}
else
{
\Session::flash('flash_error_message','Destination Updation Failed!!');
}
}
I'm stuck at this code; please give a solution
Have you added enctype="multipart/form-data" to your <form> tag? Or if you're using the Form builder, 'files' => true?
Input::file('dest_img') is not an object. You might have not loaded the classes that define Input. Check that laravel is bootstrapped correctly.
Related
The project works fine on my localhost but has issues on a live shared server.
I have tried adding this code to my index.php
// set the public path to this directory
$app->bind('path.public', function() {
return __DIR__;
});
I have tried adding this code in a new sym.php file in my public folder
<?php
$targetFolder = $_SERVER['DOCUMENT_ROOT'].'/storage/app/public';
$linkFolder = $_SERVER['DOCUMENT_ROOT'].'/public/storage';
symlink($targetFolder,$linkFolder);
echo 'Symlink process successfully completed';
?>
I have tried adding this on my web.php and then running site/linkstorage
Route::get('/linkstorage', function () {
Artisan::call('storage:link');
});
None of these solutions works
here is a snippet of my Controllers code:
public function storeBrand(Request $request){
$this->validate($request, ['brand_name'=> 'required',
'brand_url'=> 'required',
'brand_image'=>'image|nullable|max:1999']);
if($request->hasFile('brand_image')){
//1 : get filename with ext
$fileNameWithExt = $request->file('brand_image')->getClientOriginalName();
//2 : get just file name
$fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
//3 : get just extension
$extension = $request->file('brand_image')->getClientOriginalExtension();
//4 : file name to store
$fileNameToStore = $fileName.'_'.time().'.'.$extension;
//upload image
$path =$request->file('brand_image')->storeAs('public/BrandImages', $fileNameToStore);
}
else{
$fileNameToStore ='noimage.jpg';
}
$brand=new Brand();
$brand->brand_name =$request->input('brand_name');
$brand->brand_url =$request->input('brand_url');
$brand->brand_image =$fileNameToStore;
$brand->save();
return redirect('/create_brand')->with('status', 'The '.$brand->brand_name.' Brand has been saved successfully. Create another one.');
Note
When an image is uploaded the path can be traced, but the image is not found, returns an empty image.
Thank you for your time and assistance.
I have got the solution:
I Wrote down this code in my web.php route file:
Route::get('/linkstorage', function () { $targetFolder = base_path().'/storage/app/public'; $linkFolder = $_SERVER['DOCUMENT_ROOT'].'/storage'; symlink($targetFolder, $linkFolder); });
After that I navigated to my url/linkstorage
It worked!!
Looking at the code in your controller, it seems correct. Perhaps the error is within your form in the Blade file associated with this method. Based on experience I tend to forget to write this and this could probably sort out your error.
Write this on the form tag.
<form action="{{ insert the route here }}" method="POST" enctype="multipart/form-data">
// insert form input fields here...
</form>
I'm using yii framework but I think this is related to PHP
In my controller, I have the following code
$model = new Events;
$model->type_id = $type_id;
$checkFileUpload = checkFileUpload($model);
the function checkFileUpload is a custom function which contains
function checkFileUpload($model)
{
$rnd = rand(0, 9999);
$uploadedFile = CUploadedFile::getInstance($model, 'image');
if($uploadedFile->error == 0)
{
$fileName = "{$rnd}-{$uploadedFile}"; // random number file name
$model->image = $fileName;
...
I got the error get property of non-object in $uploadedFile->error.
I've tried to use reference to the model instead, but it is deprecated and does not work for me.
If I use the code of the called function (checkFileUpload) within the controller code, it works fine. I suspect that object is not passed in a correct way.
Any help?
This is because your call to CUploadedFile::getInstance returns null and not the instance you desired.
Null is returned if no file is uploaded for the specified model attribute.
— Yii Documentation
It seems like your file was not correctly uploaded. I am not a Yii Framework user, but the documentation states:
The file should be uploaded using CHtml::activeFileField.
— Yii Documentation
So you should verify that the file was actually correctly uploaded with the proper method from the Yii Framework.
PS: Objects are always passed by reference.
$model = new Events;
$type_id=$model->type_id;
$checkFileUpload = checkFileUpload($model);
function checkFileUpload($model)
{
$rnd = rand(0, 9999);
$uploadedFile = CUploadedFile::getInstance($model, 'image');
if(!isset($uploadedFile->getHasError()))
{
$fileName = "{$rnd}-{$uploadedFile}"; // random number file name
$model->image = $fileName;
The problem occurred because at the time when you are using $uploadedFile->error,the value of $uploadedFile is null.
The following line is not giving you the desired value
$uploadedFile = CUploadedFile::getInstance($model, 'image');
Which means no file has been uploaded.
Try CVarDumper::dump($_FILES,10,true);
This will tell you whether the problem is with the UPLOADING OF THE FILE or GETTING THE DETAILS OF THE UPLOADED FILE
you cant access the private property $_error $uploadedFile->_error if you are trying to. you must call $uploadedFile->getError() in your code. Also $uploadedFile will return null if no file uploaded so you must take care of that as well.
$rnd = rand(0, 9999);
$uploadedFile = CUploadedFile::getInstance($model, 'image');
if(!empty($uploadedFile) && !$uploadedFile->getHasError())
{
$fileName = "{$rnd}-{$uploadedFile}"; // random number file name
$model->image = $fileName;
will work for you.
I'm trying to make a form to upload a file, an excel file,
this is my html
<h2>Agregar Torneo</h2>
{{Form::open('admin/addtorneo', 'POST',array('files' => 'true', 'enctype' => "multipart/form-data"))}}
{{Form::label('cvs', 'Archivo:')}}
{{Form::file('cvs')}}
{{Form::submit('Subir')}}
{{Form::close()}}
and the php
$file = Input::file('cvs');
$destinationPath = 'uploads/'.Str::random(5);
$filename = Input::file('cvs.name');
$uploadSuccess = Input::file('cvs')->move($destinationPath, $filename);
$new = new Torneo;
$new->nombre = $filename;
$new->dir = $destinationPath;
$new->save();
return "Torneo agregado <br> <a href='../admin'>Volver</a>";
but I keep getting
Call to a member function move() on a non-object
I tried using $file->getClientOriginalName() instead of Input::file('cvs.name') but I get Call to a member function getClientOriginalName() on a non-object, It seems to me that the form isn't right and it ain't reciving the file correctly
Just call Input::file('cvs') one time, the second time it becomes null object.
example :
$file = Input::file('cvs');
$destinationPath = 'uploads/'.Str::random(5);
$file->move($destinationPath);
It works.
this might be a bit of a novice question and here is my situation:
i have a upload form for uploading images. and in my editAction i do:
if ($request->isPost()) {
if (isset($_POST['upload_picture']) && $formImageUpload->isValid($_POST)) {
//here i will add the picture name to my database and save the file to the disk.
}
}
$picVal = $this->getmainPic(); // here i do a simple fetch all and get the picture that was just uploaded
$this->view->imagepath = $picVal;
what happens is that the newly uploaded picture doesn't show. I checked the database and the dick and the file is there.
im thinking the problem might be the order of the requests or something similar.
any ideas?
edit: another thing is that in order to make the new image come up i have to do a SHIFT+F5 and not only press the browser refresh button
edit2: more code
i first call the upload to disk function then if that returns success addthe file to the database
$x = $this->uploadToDiskMulty($talentFolderPath, $filename)
if($x == 'success'){
$model->create($data);
}
the upload function
public function uploadToDiskMulty($talentFolderPath, $filename)
{
// create the transfer adapter
// note that setDestiation is deprecated, instead use the Rename filter
$adapter = new Zend_File_Transfer_Adapter_Http();
$adapter->addFilter('Rename', array(
'target' => $filename,
'overwrite' => true
));
// try to receive one file
if ($adapter->receive($talentFolderPath)) {
$message = "success";
} else {
$message = "fail";
}
return $message;
}
If the picture only appears when you do SHIFT+F5 that means it's a caching problem. Your browser doesn't fetch the image when you upload it. Do you use the same file name?
I want to upload an image in Zend-framework.
In Application_Form_Test.php I write following code....
uploadImage = new Zend_Form_Element_File('uploadImage');
$uploadImage->setLabel("Upload Image ")
->setRequired(true)
->addValidator('Extension', false, 'jpeg,png')
->getValidator('Extension')->setMessage('This file type is not supportted.');
In the testAction() I write following code.....
$upload = new Zend_File_Transfer_Adapter_Http();
$upload->addValidator('Size', false, 52428800, 'image');
$upload->setDestination('uploads');
$files = $upload->getFileInfo();
foreach ($files as $file => $info) {
if ($upload->isValid($file)) {
$upload->receive($file);
}
}
Code is running successfully But I am not getting that image to the destination folder?
What may be the problem....?
Please help me.....
Thanks in advance....
I don't think that the getFileInfo() method is supposed to actually execute the file upload. I believe that in your controller action, you have to either call the getValues() method on the form object, or call the receiveFile() method on the form element.
See http://framework.zend.com/manual/en/zend.form.standardElements.html#zend.form.standardElements.file for the documentation examples.
An additional note: if you look in Zend_Form_Element_File->receive(), you will see that isValid() is called, so there's no need to clutter your controller with it. Here's what I do:
if ($upload->receive()) {
if ($upload->getFileName() && !file_exists($upload->getFileName())) {
throw new Exception('The upload should have worked, but somehow did not!');
}
} else {
throw new Exception(implode(PHP_EOL, $upload->getErrors()) . implode(PHP_EOL, $upload->getErrorMessages()));
}