Laravel: Undefined value on image upload - php

First Laravel Project. I building a feature where I can upload an image. Everything what I did is based on this PDF (page 98-101)
My blade.php
<?php echo Form::open(array('url' =>'/product/imgedit','files'=>'true'));
echo 'Adj meg egy új képet';
echo Form::file('image');
echo Form::submit('Upload File');
echo Form::close();?>
My router
Route::get('product/{id}/imgedit', 'InventoryController#imgreq');
Route::post('product/imgedit', 'InventoryController#imgupl');
My Controller:
public function imgreq($id)
{
$product = DB::select('select * FROM inventory WHERE barcode = ?', [$id]);;
return view('productimgupl', ['product' => $product]);
}
public function imgupl()
{
$file = $request->file('image');
//Display File Name
echo 'File Name: ' . $file->getClientOriginalName();
echo '<br>';
//Display File Extension
echo 'File Extension: ' . $file->getClientOriginalExtension();
echo '<br>';
//Display File Real Path
echo 'File Real Path: ' . $file->getRealPath();
echo '<br>';
//Display File Size
echo 'File Size: ' . $file->getSize();
echo '<br>';
//Display File Mime Type
echo 'File Mime Type: ' . $file->getMimeType();
//Move Uploaded File
$destinationPath = '/media/productimg/';
$file->move($destinationPath, $file->getClientOriginalName());
}
Error message:
ErrorException in InventoryController.php line 28: Undefined variable:
request
What I did wrong?

You need to bring in the Request object in your method's argument. Like so:
public function imgupl(Request $request) {
// code...
}
Then you may use $request in the method.
By default Laravel includes this class when you use php artisan make:controller by inserting it at the top of your Controller with this line: use Illuminate\Http\Request;. All you are doing is casting the Request object to a variable named $request for use in that method.
Hope this helps!

Related

ImageIntervention & Laravel 9: file_put_contents ERROR Failed to open stream: No such file or directory

I'm using Laravel 9 and Image Intervetion to resize uploaded images:
public static function resize($file, $fileName)
{
$path = self::route();
foreach (self::size() as $key => $value) {
$resizePath = self::route() . "{$value[0]}x{$value[1]}_" . $fileName;
Image::make($file->getRealPath())
->resize($value[0], $value[1], function ($constraint) {
$constraint->aspectRatio();
})
->save(storage_path($resizePath));
$urlResizeImage[] = ["upf_path" => $resizePath, "upf_dimension" => "{$value[0]}x{$value[1]}"];
}
self::$urlResizeImage = $urlResizeImage;
}
But the line ->save(storage_path($resizePath)); returns this error:
Can't write image data to path
So in the Image Facade of Intervention, there's a #file_put_contents:
public function save($path = null, $quality = null, $format = null)
{
$path = is_null($path) ? $this->basePath() : $path;
// dd($path);
if (is_null($path)) {
throw new NotWritableException(
"Can't write to undefined path."
);
}
if ($format === null) {
$format = pathinfo($path, PATHINFO_EXTENSION);
}
$data = $this->encode($format, $quality);
$saved = #file_put_contents($path, $data);
if ($saved === false) {
throw new NotWritableException(
"Can't write image data to path ({$path})"
);
}
// set new file info
$this->setFileInfoFromPath($path);
return $this;
}
And I tried removing # from #file_put_contents to see what's going wrong here, but then I got this:
file_put_contents(C:\xampp\htdocs\project\storage\upload/1401/11/images/questions/107200x200_1671289517402.jpg): Failed to open stream: No such file or directory
So it basically says that it can not find the $path and when I uncomment dd($path), this is the output:
C:\xampp\htdocs\project\storage\upload/1401/11/images/questions/108200x200_1671289517402.jpg
So what's going wrong here?
How can I properly save the resized images into this directory?
Please I beg you to help me with this because it's been a week that I'm struggling with this error and got headache!
UPDATE #1:
Here is the route():
public static function route()
{
return "upload/" . jdate()->format('Y') . "/" . jdate()->format('m') . "/" . self::$typeFile . "/" . strtolower(self::$catType)."s" . "/" . self::$objId;
}
And I changed it to this:
public static function route()
{
return "upload".DIRECTORY_SEPARATOR.jdate()->format('Y').DIRECTORY_SEPARATOR.jdate()->format('m').DIRECTORY_SEPARATOR.self::$typeFile.DIRECTORY_SEPARATOR.strtolower(self::$catType)."s".DIRECTORY_SEPARATOR.self::$objId;
}
But still the same error occurs :(

laravel how to delete file in storage when we delete data

I have some problem to delete file when some value deleted.
This is my delete function:
public function delete($id, Adopsi $adopsi)
{
Storage::delete('post/adopsi/' . $adopsi->image_post_adps);
$data = Adopsi::where('id', $id)->delete();
if ($data) {
return redirect()->route('adopsi.index')->with('success', 'Data telah dihapus');
} else {
return redirect()->route('adopsi.index')->with('error', 'Data gagal dihapus');
}
}
This is how I store my image before:
$imageSize = $request->file('image_post_adps')->getSize();
$imageName = $request->file('image_post_adps')->getClientOriginalName();
$request->file('image_post_adps')->storeAs('public/post/adopsi', $imageName);
directory folder where is use to save:
storage/app/public/post/adopsi/..... (there's my file),
I've used Storage::delete() and unlink() but it still isn't working.
Your images are stored at 'public' disk path. But disk is not specified in delete()
Try
Storage::disk('public')->delete('post/adopsi/' . $adopsi->image_post_adps);
First, make sure the file exists by building the path:
First of all, add the File Facade at the top of the controller:
use Illuminate\Support\Facades\File;
You can use public_path() & storage_path():
$path = public_path('../storage/YOUR_FOLDER_NAME/YOUR_FILE_NAME');
if (!File::exists($path)) {
File::delete(public_path('storage/YOUR_FOLDER_NAME/YOUR_FILE_NAME'));
}
$path = storage_path().'/app/public/post/adopsi/'.$db->image;
if(File::exists($path)) {
File::delete($path);
}
The below worked for me
$destinationPath = storage_path() . '/app/public/images/products';
File::delete($destinationPath . '/' . $product->id . '.' . $fileExtension);

hasFile function not working in laravel 5.4

i am trying to upload a photo using Image Intervention Package
i tried dd($request->hasFile('avator') ) and it return false
i returned "error" in my if statment just to make sure that i have an error
thanks in advance
public function update_photo(Request $request){
if($request->hasFile('avator') ){
$avator = $request->file('avator');
$filename = time() . '.' . $pic->getClientOriginalExtension();
Image::make($avator)->resize(300 , 300)->save(public_path('/uploads/avators' . $filename));
$user = Auth::user();
$user->avator = $filename ;
$user->save();
echo "hello world !";
}else {
echo " Error"; // just to make sure that i have an error
}
return view("profile" , array("user" => Auth::user() ));
}
first edit this line of code
$filename = time() . '.' . $avator->getClientOriginalExtension();
add to this slash also
Image::make($avator)->resize(300 , 300)->save(public_path('/uploads/avators/' . $filename));
*in your blade template make sure of spelling you are writing avator not avatar *
<input type="file" name="avator"/>
In your blade put this in your form tag:
enctype="multipart/form-data
and in your controller:
use File;

Uploading multiple image with different input file in Codeigniter

So I have four input files in my forms and I send it on my global $_FILES with the following indices: front,rear,right and left.
I want to upload these using codeigniter image class library. This is my code:
public function upload_to_temp($id, $folder, $tags){
$path = realpath(APPPATH . '../public/resources/temps/' . $folder );
//makes a directory
mkdir($path . '/' . $id, 0700);
//navigate to the newly created path
$path = realpath(APPPATH . '../public/resources/temps/' . $folder . '/' . $id);
if(isset($tags)){
//use these tags to check the files present on submission
foreach($tags as $tag){
if(array_key_exists($tag,$_FILES)){
if(!empty($_FILES) && $_FILES[$tag]["name"] != "" && isset($_FILES[$tag]["name"])){
$config = array (
'source_image' => $_FILES[$tag]["name"],
'image_library' => 'gd',
'upload_path' => $path,
'file_name' => $id . '_' . $tag . '.jpg',
'allowed_types' => 'png|jpg|jpeg',
'overwrite' => TRUE,
'max_size' => '2000',
);
$this->_CI->upload->initialize($config);
if(!$this->_CI->upload->do_upload()){
echo 'Error creating image. ';
echo $this->_CI->upload->display_errors();
}else{
echo 'Success saving to temp folder';
}
//kapag failed
if(!$this->_CI->upload->do_upload()){
echo 'Error creating image.';
echo $this->_CI->upload->display_errors();
}else{
//now, the $path will become our resource path for copying and creating thumbnails.
$resouce_path = $config['upload_path'] . '/' . $config['file_name'];
$this->img_create_thumb($resouce_path, $folder);
}
}else{
//Hindi na dapat marating to!
echo $tag . ' not present ';
}
}else{
//use default pictures
echo $tag . ' not present ';
}
}
}
}
However it gives me the following error:
Error creating image. You did not select a file to upload.Error
creating image.You did not select a file to upload.You did
not select a file to upload.Error creating image. You did not
select a file to upload.Error creating image.You did not select
a file to upload.You did not select a file to upload.right
not present left not present
I think I did not correctly specified which resource on the $_FILES should be uploaded.
Your response would be greatly appreciated.
Thanks
I solved it by supplying the indices in codeigniter's do_upload()
$this->_CI->upload->do_upload($tag);

I am trying to download a file from mysql, I saved the file location in the database, now I am trying to make a download link for the user on my page

Unable to create the download link. I am fetching the path saved from database and then try to make a link for it to download, but nothing happens.
Below is my code:
$query_print="SELECT vitae_pi FROM pi WHERE username='t124'";
$query_print_run=mysqli_query($conn,$query_print);
$query_print_recordset=mysqli_fetch_assoc($query_print_run);
$query_print_path=$query_print_recordset['vitae_pi'];
echo ' this is file path '.$query_print_path;
Here I am simply trying to create the download link for user t124, instead of using the current user for testing purposes?
This is hyperlink code:
<?php echo "<a href='".$query_print_path."'>".DOWNLOAD."</a>"; ?>
Any suggestions?
This my move file function:
protected function moveFile($file)
{
$filename = isset($this->newName) ? $this->newName : $file['name'];
//echo $filename;
$success = move_uploaded_file($file['tmp_name'], $this->destination . $filename);
if ($success) {
$result = $file['name'] . ' was uploaded successfully';
if (!is_null($this->newName)) {
$_SESSION['current_filename']=$this->newName;
echo $_SESSION['current_filename'];
$result .= ', and was renamed ' . $this->newName;
}
else{
$_SESSION['current_filename']=$file['name'];
echo $_SESSION['current_filename'];
}
//$result .= '.';
//echo $this->newName;
$this->messages[] = $result;
} else {
$this->messages[] = 'Could not upload ' . $file['name'];
}
}
Updating the table with file path:
$file_path_variable1= $destination1.$_SESSION['current_filename'];
echo '$file_path_variable1 : '.$file_path_variable1;
$query1="UPDATE proposal SET whitepaper_prop='$file_path_variable1' WHERE userName_prop='$currentuser'";
$result_query1=mysqli_query($conn,$query1);
....................
SOLUTION CODE IS:
Solution code is :
$query_print="SELECT vitae_pi FROM pi WHERE username='t115'";
$query_print_run=mysqli_query($conn,$query_print);
$query_print_recordset=mysqli_fetch_assoc($query_print_run);
$query_print_path=$query_print_recordset['vitae_pi'];
$dir= 'uploaded/';
$path=opendir($dir);
<?php
}while($query_pi_array=mysqli_fetch_assoc($query_pi_result));?>
<div>
<?php while($file=readdir($path)){
if($file != "." || $file !=".."){
if($file==$query_print_path){ ?>
Proposal Whitepaper
What does this display ?
<?php echo "<a href='".$query_print_path."'>".DOWNLOAD."</a>"; ?>
DOWNLOAD should be part of the PHP string, if not, it will be considered as a constant :
<?php echo "<a href='".$query_print_path."'>DOWNLOAD</a>"; ?>
Also, use double quotes for HTML attributes :
<?php echo "DOWNLOAD"; ?>
And the optimized way (to avoid useless string parsing) :
<?php echo 'DOWNLOAD'; ?>

Categories