upload an image through an api using in laravel - 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.

Related

How to read file Laravel?

I load file using this:
public function fileUpload(Request $req)
{
$req->validate([
'file' => 'required|mimes:csv,txt,xlx,xls,pdf|max:2048'
]);
$fileModel = new File();
if ($req->file()) {
$fileName = time() . '_' . $req->file->getClientOriginalName();
$filePath = $req->file('file')->storeAs('uploads', $fileName, 'public');
$fileModel->name = time() . '_' . $req->file->getClientOriginalName();
$fileModel->file_path = '/storage/' . $filePath;
$fileModel->save();
$this->read($fileModel->file_path);
return back()
->with('success', 'File has been uploaded.')
->with('file', $fileName);
}
}
Then I tried to read file after upload file:
public function read($path)
{
$file = FileStorage::get($path);
dd($file);
}
But I get this error:
File does not exist at path /storage/uploads/1654468183_test.csv.
How to specify path properly?
I would do this way:
if ($req->file()) {
$fileName = time() . '_' . $req->file->getClientOriginalName();
$filePath = $req->file('file')->storeAs('uploads', $fileName, 'public');
$fileModel->name = $fileName; //<--set the right filename
$fileModel->file_path = '/storage/app/public/' . $filePath;
$fileModel->save();
$this->read($fileModel->file_path);
return back()
->with('success', 'File has been uploaded.')
->with('file', $fileName);
}
change this line
$filePath = $req->file('file')->storeAs('uploads', $fileName, 'public');
to this
$filePath = $req->file('file')->storeAs('uploads/', $fileName, 'public');

some images gets duplicated after the uploading - laravel

i am using a function that uploads multiple images and it was working perfectly locally but after deployment i am having this duplication issue .
i upload img1 and img2 and img3 but in the database i find only one of them like img1.jpg and the same thing in the folder .
public function _articleGalleryUpload(Request $request)
{
$article = Blog::find($request->id);
$img = $request->Otitle;
//dd($img);
$request->validate([
'images'=> 'required',
'images.*'=> 'image|mimes:jpg,png,jpeg|max:4000'
]);
if(!File::isDirectory('assets/images/blogs/gallery/'.$img)){
File::makeDirectory('assets/images/blogs/gallery/'.$img);
}
$images = $request->file('images');
if($request->hasFile('images'))
{
foreach( $images as $image )
{
//$extension = $file->getClientOriginalExtension();
$ImageName = '_' . time() .'.' . $image->getClientOriginalExtension();
$path = $image->move(('assets/images/blogs/gallery/'.$img), $ImageName);
$imageP = Image::make($path)->resize(600, null, function ($constraint) {
$constraint->aspectRatio();
});
$galerie = new blogsGallery;
$galerie->Img = $ImageName;
$galerie->idart = $request->id;
$galerie->alt = $img;
$imageP->save();
$galerie->save();
}
return back()->with('success', 'les images ont été téléchargées');
}
}
i tried using array to store the names of the images but it didn't work, it uploads one image instead of multiple .
Your code has one issue.
$path = $image->move(('assets/images/blogs/gallery/'.$img), $ImageName);
this code is error.
$img is one name for several images.

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

How to upload image in array input type

I want to upload image using protected function create(array $data){}
Below code is used for public function create(Request $request){}
public function create(Request $request)
{
$image = new Image();
if ($request->hasFile('image')) {
$dir = 'uploads/';
$extension = strtolower($request->file('image')->getClientOriginalExtension()); // get image extension
$fileName = str_random() . '.' . $extension; // rename image
$request->file('image')->move($dir, $fileName);
$image->image = $fileName;
}
$image->save();
return view('here');
}
}
I tried the following code but gets error
protected function create(array $data)
{
$dir = '/customer/images/';
$extension = strtolower($data['image']->getClientOriginalExtension()); // get image extension
$fileName = str_random() . '.' . $extension; // rename image
$data['image']->move($dir, $fileName);
$data['image'] = $fileName;
return Image::create([
'image' => $data['image'],
]);
}
I'm getting error. How can i upload image using array.

Resources