Image not show in browser with Lumen Api - laravel

I use Lumen to get images and show in browser, my code in controller is :
use Illuminate\Support\Facades\File;
$photo = $this->uploadFile->get_by_photo($photo, ['filename']);
$path = storage_path('app') . '/' . $photo[0]['filename'];
$file = File::get($path);
$type = File::mimeType($path);
$response = response()->make($file, 200);
$response->header("Content-Type", $type);
return $response;
But image not show in browser , i just got a dark page when run that api

this code works:
$photo = $this->uploadFile->get_by_photo($photo, ['filename']);
$path = storage_path('app') . '/' . $photo[0]['filename'];
$type = File::mimeType($path);
$headers = array('Content-Type' => $type);
$response = response()->download($path, $photo, $headers);
ob_end_clean();
return $response;

Related

upload an image through an api using in laravel

i have 2 web systems here,system a and system b.when i upload an image on system a i want as well send the image to system b.i am using an api to achieve the logic.am able to upload the image in system a perfectly but its unable be pushed to system b.am using guzzle http client to send the image to the api on upload.the upload on system a works very well but the data is being saved in system b.i have tested the api store function in postman and i get i 200ok status code but the data isnt being saved in the specific table in system b database.
here is my image save function in system a which works perfectly,it generates a folder which stores the image and a thumbnail folder inside the main folder where the thumbnail is stored.
public function productSavePicture(Request $request)
{
try {
$validation = Validator::make($request->all(), [
'product_id' => 'required',
]);
if ($validation->fails()) {
throw new \Exception("validation_error", 19);
}
$product_details = product::where('systemid', $request->product_id)->first();
if (!$product_details) {
throw new \Exception('product_not_found', 25);
}
if ($request->hasfile('file')) {
$file = $request->file('file');
$extension = $file->getClientOriginalExtension(); // getting image extension
$company_id = Auth::user()->staff->company_id;
if (!in_array($extension, array(
'jpg', 'JPG', 'png', 'PNG', 'jpeg', 'JPEG', 'gif', 'GIF', 'bmp', 'BMP', 'tiff', 'TIFF'))) {
return abort(403);
}
$filename = ('p' . sprintf("%010d", $product_details->id)) . '-m' . sprintf("%010d", $company_id) . rand(1000, 9999) . '.' . $extension;
$product_id = $product_details->id;
$this->check_location("/images/product/$product_id/");
$file->move(public_path() . ("/images/product/$product_id/"), $filename);
$this->check_location("/images/product/$product_id/thumb/");
$thumb = new thumb();
$dest = public_path() . "/images/product/$product_id/thumb/thumb_" . $filename;
$thumb->createThumbnail(
public_path() . "/images/product/$product_id/" . $filename,
$dest,
200);
$systemid = $request->product_id;
$product_details->photo_1 = $filename;
$product_details->thumbnail_1 = 'thumb_' . $filename;
$product_details->save();
// push image to system b on saving
$client = new \GuzzleHttp\Client();
$url = "http://systemb/api/push_h2image";
$response = $client->request('POST',$url,[
'multipart' => [
[
'Content-type' => 'multipart/form-data',
'name' => $filename,
'contents' => file_get_contents( public_path() . "/images/product/$product_id/".$filename)
],
]
]);
} else {
return abort(403);
}
} catch (\Exception $e) {
if ($e->getMessage() == 'validation_error') {
return '';
}
if ($e->getMessage() == 'product_not_found') {
$msg = "Error occured while uploading, Invalid product selected";
}
{
$msg = $e->getMessage();
}
$data = view('layouts.dialog', compact('msg'));
}
return $data;
}
here is my route for the api
Route::post(/push_productimage','APIController#savesystemAimage')->name(pushproductimage');
here is the api function in system b where the image and thumbnail should be recieved and stored to system b database
public function savesystemAimage(Request $request)
{
$productdetails=new Product;
if ($request->hasfile('file')) {
$file = $request->file('file');
$extension = $file->getClientOriginalExtension();
$filename = ('p' . sprintf("%010d", $productdetails->id)) . '-m' . rand(1000, 9999) . '.' . $extension;
$product_id = $productdetails->id;
$this->check_location("/images/product/$product_id/");
$file->move(public_path() . ("/images/product/$product_id/"), $filename);
$this->check_location("/images/product/$product_id/thumb/");
$thumb = new thumb();
$dest = public_path() . "/images/product/$product_id/thumb/thumb_" . $filename;
$thumb->createThumbnail( public_path() . "/images/product/$product_id/" . $filename,
$dest,200);
$systemid = $request->product_id;
$productdetails->photo_1 = $filename;
$productdetails->thumbnail_1 = 'thumb_' . $filename;
$productdetails->save();
}
}
i dont know why the api function is not storing the data yet on postman it shows a 200ok status code but the image and thumbnail isnt saved.

RESOLVED Laravel 8 Update image and delete old image

I need help with a little thing.
I have a product table with an image:
Here is my function store which works perfectly
$fileName = null;
if (request()->hasFile('image')) {
$image = request()->file('image');
$fileName = md5($image->getClientOriginalName() . time()) . "." . $image->getClientOriginalExtension();
$image->move('./img/', $fileName);
}
Product::create([
'title' => $request->input('title'),
'subtitle' => $request->input('subtitle'),
'description' => $request->input('description'),
'price' => $request->input('price'),
'image' => $fileName,
]);
I am trying to modify the image in update but I do not know how to do it and I am in difficulty currently
Here is my update function where the image is missing to modify it and delete the old one
public function update(Request $request, Product $product)
{
$product->title = $request->input('title');
$product->subtitle = $request->input('subtitle');
$product->description = $request->input('description');
$product->price = $request->input('price');
$product->save();
Thanks
You can modify your update function like this
public function update(Request $request, Product $product)
{
$fileName = null;
$currentImage = $product->image;
if (request()->hasFile('image')) {
$image = request()->file('image');
$fileName = md5($image->getClientOriginalName() . time()) . "." . $image->getClientOriginalExtension();
$image->move('./img/', $fileName);
}
else
$fileName = $currentImage
if($fileName && $currentImage)
{
// Delete the old file i.e $fileName
}
$product->title = $request->input('title');
$product->subtitle = $request->input('subtitle');
$product->description = $request->input('description');
$product->price = $request->input('price');
$product->image = $fileName;
$product->save();
}
It's good with this :
$fileName = null;
$currentImage = $product->image;
if (request()->hasFile('image')) {
$image = request()->file('image');
$fileName = md5($image->getClientOriginalName() . time()) . "." . $image->getClientOriginalExtension();
$image->move('./img/', $fileName);
}
else
$fileName = $currentImage;
if($fileName && $currentImage)
{
Storage::delete('./img/' . $currentImage);
}
Thanks

Laravel upload gifs

i am uploading gif for my posts in laravel but gif is like an image its not moving or something like this
<?php
if($request->hasFile('gif')){
$gif = $request->file('gif');
$gif_filename = time() . '.' . $gif->getClientOriginalName();
$gif_location = public_path('/images/' . $gif_filename);
Image::make($gif)->save($gif_location);
}
$post->gif = $gif_filename;
$post->save();
?>
here is the code what I am using I think everything is kinda correct
I use this method
if(Input::hasFile('imagen')) {
$time = Carbon::now()->format('Y-m-d');
$image = $request->file('imagen');
$extension = $image->getClientOriginalExtension();
$name = $image->getClientOriginalName();
$fileName = $time."-".$name;
$image->move(storage_path(),$fileName);
}
Please try this and let me know how it works :)
An easy way to update and save is to do it like this:
public function store(Request $request)
{
$imgLocation = Storage::disk('public')->put(time() . '.' . $request->file('image')->getClientOriginalName(), $request->gif), $request->file('gif'));
// This would save it to the gifs table if you need something like it, otherwise skip this creation
$gif= Gif::create([
'name' => $request->name,
'path' => $imgLocation
]);
if ($gif) {
return response()->json("Success!");
}
return response()->json("Error!"); // or you return redirect()...
}
$image = $request->file('image');
if(isset($image)) {
if($image->getClientOriginalExtension()=='gif'){
$image = $request->file('image');
$extension = $image->getClientOriginalExtension();
$name = $image->getClientOriginalName();
$fileName = 'exerciseimages'."-".$name;
$image->move('storage/courseimages/',$fileName);
}
else{
$fileName = 'exerciseimages'.'-'.uniqid().'.'.$image->getClientOriginalExtension();
if(!Storage::disk('public')->exists('courseimages')){
Storage::disk('public')->makeDirectory('courseimages');
}
$amenitiesimg = Image::make($image)->resize(250,250)->stream();
Storage::disk('public')->put('courseimages/'.$fileName, $amenitiesimg);
}
}
else {
$fileName = 'default.png';
}

Laravel deploy: storage image doesn't work correctly

After deploying my laravel project from local to Apache web server, all works correctly except images link. Here the code:
Images are stored in:
storage/app/public/photos
after i've run command:
php artisan storage:link
Images are linked at:
public/storage/photos
Controller:
if ($request->hasFile('photo')) {
$extension = $request->file('photo')->getClientOriginalExtension();
$file = $request->file('photo');
$photo = $file->storeAs('public/photos', 'foto-' . time() . '.' . $extension);
$user->photo = $photo;
$user->save();
}
Images are uploaded correctly on storage/app/public/photos and correctly linked in public/storage/photos but it doesn't display on frontend.
in blade, i've tried to use Storage::url to retrieve the path
{{Storage::url($user->photo)}}
and asset()
{{asset($user->photo)}}
in both cases, image doesn't exist
The public path of image is:
http://mywebsite.com/storage/photos/foto-1522914164.png
You should Use url function to show your image like below way.
url($user->photo);
I'd suggest to change the controller code as follows:
if ($request->hasFile('photo')) {
$extension = $request->file('photo')->getClientOriginalExtension();
$file = $request->file('photo');
$photoFileName = 'foto-' . time() . '.' . $extension;
$photo = $file->storeAs('public/photos', $photoFileName);
$user->photo = 'photos/' . $photoFileName;
$user->save();
}
Then you can use {{asset($user->photo)}} in your blade.
on my webspace, it seems that the only way to display image correctly is to create a custom route that read and serve the image.
i'm solved like this:
i'm storing only image name in db:
if ($request->hasFile('photo')) {
$extension = $request->file('photo')->getClientOriginalExtension();
$file = $request->file('photo');
$photoFileName = 'photo-' . $model->id . '.-' . time() . '.' . $extension;
$photo = $file->storeAs('public/photos', $photoFileName);
$store = $photoFileName;
}
then, i've create custom route that read images and display them:
Route::get('storage/{filename}.{ext}', function ($filename, $ext) {
$folders = glob(storage_path('app/public/*'), GLOB_ONLYDIR);
$path = '';
foreach ($folders as $folder) {
$path = $folder . '/' . $filename . '.' . $ext;
if (File::exists($path)) {
break;
}
}
if (!File::exists($path)) {
abort(404);
}
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header('Content-Type', $type);
return $response;
});
in blade, i'm using Storage to display image:
{{ Storage::url($photo->photo) }}}

facebook app losing session values after redirection

I am using Facebook PHP SDK 3.1.1
This page is supposed to collect value from header and later use it for uploading images.
Problem: $_SESSION['file'] becomes null after user logs in to Facebook.
<?php
require 'facebook.php';
include('connect.php');
$facebook = new Facebook(array('appId' => "XXXXXX",'secret' => "XXXXX","cookie" => true,'fileUpload' => true));
session_start();
$user_id = $facebook->getUser();
if(isset($_REQUEST["src"]))
{
echo "<center><img src='loader.gif'/></center>";
echo "<center><div id='msg'>Exporting Image..</div></center>";
$_SESSION['file'] = $_REQUEST["src"];
$_SESSION['club'] = $_REQUEST["club"];
}
$code = $_REQUEST["code"];
if(empty($code))
{
$_SESSION['state'] = md5(uniqid(rand(), TRUE));
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id=". $app_id . "&redirect_uri=" . urlencode($my_url) . "&state=". $_SESSION['state'];
echo("<script> top.location.href='" . $dialog_url . "'</script>");
exit();
}
$token_url = "https://graph.facebook.com/oauth/access_token?". "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url). "&client_secret=" . $app_secret . "&scope=user_photos,email,read_stream,publish_stream&code=".$code;
function url_get_contents ($Url) {
if (!function_exists('curl_init')){
die('CURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
$response = url_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = "https://graph.facebook.com/me?access_token=". $params['access_token'];
$user = json_decode(url_get_contents('https://graph.facebook.com/me/albums?access_token='.$params['access_token']),true);
foreach($user as $key=>$value)
{
foreach($user[$key] as $key1=>$value1)
{
if($value1['name'] == "Photos")
{
$album_uid = $value1['id'];
}
}
}
if(!isset($album_uid))
{
echo 'Create an album';
$album_details = array(
'message'=> 'Uploaded via XXX',
'name'=> 'Photos'
);
$create_album = $facebook->api('/me/albums', 'post', $album_details);
$album_uid = $create_album['id'];
}
$photo_details = array('message'=>$_SESSION["club"]);
try{
$file = NULL;
$file="../Photos/".$_SESSION['file'].".jpeg";
echo '<script>document.getElementById("msg").innerHTML = "Uploading Image"</script>';
$photo_details['image'] = '#' . realpath($file);
$upload_photo = $facebook->api('/'.$album_uid.'/photos', 'post', $photo_details);
}catch(Exception $e){
echo "<script type='text/javascript'>top.location.href = 'http://www.facebook.com/PAGE_URL/';</script>";
exit();
}
$_SESSION['file'] is null
Am I doing it right ? or something is wrong with my web hosting ?
The problem is that your app is running inside of an IFRAME and the session cookies are not being preserved. Please see here:
Facebook Iframe App with multiple pages in Safari Session Variables not persisting

Resources