Trying to upload multiple images using guzzlehttp client in laravel - php

I am trying to upload multiple images using guzzlehttp client. I have a form in which other type of data('id', 'date','name' e.t.c..) and images are there.
I want to save other data along with image upload through an Api Request.
I am able to save other data, but i am getting problem in uploading images.
In the API i am accessing my image file by
$request->file('images')
but it is showing empty.
My code for calling the API
$images = $request->file('images');
foreach ($images as $image)
{
$body[] = [
'Content-type' => 'multipart/form-data',
'name' => $image->getClientOriginalName(),
'contents' => fopen($image->getRealPath(), 'r')
];
}
$data = $request->all();
$client = new Client();
$response = $client->request('POST', $url, [
'multipart' => $body,
'json' => $data
]);
I'm handling the Api for uploading image below
if ($request->hasFile('images'))
{
$images = $request->file('images');
foreach ($images as $image)
{
$imageRules = [
'file' => 'mimes:png,jpeg,jpg,JPG|max:1024'
];
$imageMessages = [
'file.mimes' => 'One of the images/video is not valid. (only .png, .jpeg, .jpg, .mp4, .x-flv, .x-mpegURL, .MP2T, .3gpp, .quicktime, .x-msvideo, .x-ms-wmv are accepted)',
'file.max' => 'Image size cannot br more than 1 MB'
];
$imageValidator = Validator::make(['file' => $image], $imageRules, $imageMessages);
if ($imageValidator->fails())
{
return response()->json(['success' => false, 'error' => $imageValidator->messages()->first(), 'dashRedirectUrl' => $redirectRoute]);
}
}
$directPath = '/ticket/' . $ticket->id . '/mapping/' . $mappingId . '/images/';
foreach ($images as $image)
{
$option = ['isWatermark' => false];
$imageName = $this->uploadImageToServer($image, $directPath, $option);
$imgInsertData = [
'url' => $imageName,
'title' => $this->getImageTitle($image),
'ticket_mapping_id' => $mappingId,
'type_id' => 1,
];
TicketMappingGallery::create($imgInsertData);
}
}
Note :: My funciton uploadImageToServer() is custom function for uploading the images..
Any help would be appreciated. Drop comment if anything is not clear.

Try this one,
foreach ($image as $img) {
$body[] = [
'name' => 'image[]',
'image_path' => $img->getPathname(),
'image_mime' => $img->getmimeType(),
'image_org' => $img->getClientOriginalName(),
'contents' => fopen($img->getRealPath(), 'r')
];
}
$requestOptions = ['query' => $data, 'multipart' => $body
];

Related

Skip image validation and creation in laravel update function

Please am trying to upload 3 different images using the code below. How do I get each of the methods that generates the unique image names to run only when their respective request fields have data or is not empty. thus the form submit should not try generating any image name for afile field when that particular file field is empty.
My update controller function
public function update(Request $request, Product $product)
{
$image = $request->file('primary_image');
$name_gen = md5(rand(1000, 10000)).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url = 'upload/products/'.$name_gen;
$image_1 = $request->file('image_1');
$name_gen = md5(rand(1000, 10000)).'.'.$image_1->getClientOriginalExtension();
Image::make($image_1)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url_1 = 'upload/products/'.$name_gen;
$image_2 = $request->file('image_2');
$name_gen = md5(rand(1000, 10000)).'.'.$image_2->getClientOriginalExtension();
Image::make($image_2)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url_2 = 'upload/products/'.$name_gen;
Product::insert([
'name' => $request->name,
'category' => $request->category,
'price' => $request->price,
'description' => $request->description,
'status' => $request -> status,
'estimated_delivery_time' => $request->estimated_delivery_time,
'available_quantity' => $request->available_quantity,
'colors' => $request->colors,
'supplier_name' => $request->supplier_name,
'supplier_phone' => $request->supplier_phone,
'video_description' => $request->video_description,
'primary_image' => $save_url,
'image_1' => $save_url_1,
'image_2' => $save_url_2,
]);
$notification = array(
'message' => 'Product updated successfully',
'alert-type' => 'success'
);
return redirect()->back()->with($notification);
}
Thanks so much for taking time to review my code
Since you are doing the same name generation process all through, you can use an array and do a foreach loop with an if condition like this:
$my_array = [$request->file('primary_image'), $request->file('image_1'), $request->file('image_2')];
foreach($my_array as $item) {
if($item) {
$image = $item;
$name_gen = md5(rand(1000, 10000)).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url = 'upload/products/'.$name_gen;
}
}
Now this will only generate names for images that are not empty.
UPDATE:
For the insert functionality, I would assume your table fields for the images can have null values, so this doesn't throw an error. Now instead of the code above, do this:
$my_array = [$request->file('primary_image'), $request->file('image_1'), $request->file('image_2')];
$insert_array = [];
foreach($my_array as $item) {
$save_url = '';
if($item) {
$image = $item;
$name_gen = md5(rand(1000, 10000)).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url = 'upload/products/'.$name_gen;
}
array_push($insert_array, $save_url);
}
Now for your insert query, do this:
Product::insert([
'name' => $request->name,
'category' => $request->category,
'price' => $request->price,
'description' => $request->description,
'status' => $request -> status,
'estimated_delivery_time' => $request->estimated_delivery_time,
'available_quantity' => $request->available_quantity,
'colors' => $request->colors,
'supplier_name' => $request->supplier_name,
'supplier_phone' => $request->supplier_phone,
'video_description' => $request->video_description,
'primary_image' => $insert_array[0],
'image_1' => $insert_array[1],
'image_2' => $insert_array[2],
]);
This would work.

Request to RingCentral API

I am trying to send a request to RingCentral API. The link to documentation is https://developers.ringcentral.com/api-reference/Fax/createFaxMessage If I don't specify faxResolution or coverIndex everything goes well, fax could be sent. But if I add faxResolution param like in the code below, I receive error "Parameter [faxResolution] value is invalid", "errorCode" : "CMN-101". The same thing with coverIndex param. My client is GuzzleHttp 6.3
$token = $this->ringcentral->platform()->auth()->data()['access_token'];
$a = array();
foreach ($destination_numbers as $number) {
$a[] = [
'name' => 'to',
'contents' => $number,
'headers' => ['Content-Type' => 'multipart/form-data']
];
}
$a[] = [
'name' => 'faxResolution',
'contents' => 'High',
'headers' => ['Content-Type' => 'multipart/form-data']
];
foreach ($attachments as $attachment) {
$file_pointer = fopen($attachment, 'r');
$mime = mime_content_type($attachment);
$a[] = [
'name' => 'attachment',
'contents' => $file_pointer,
'headers' => ['Content-Type' => $mime]
];
}
$client = new Client();
try {
$response = $client->request('POST', url(config('services.ringcentral.app_url')) . '/restapi/v1.0/account/~/extension/~/fax', [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $token
],
'multipart' => $a
]);
$response = json_decode($response->getBody(), true);
} catch (\GuzzleHttp\Exception\ClientException $e) {
echo($e->getResponse()->getBody()->getContents());
}
Here's what RingCentral suggests when using PHP. I included all of what they suggested, but just look at the part about faxResolution (2/3 of the way down)
<?php
// https://developers.ringcentral.com/my-account.html#/applications
// Find your credentials at the above url, set them as environment variables, or enter them below
// PATH PARAMETERS
$accountId = '<ENTER VALUE>';
$extensionId = '<ENTER VALUE>';
$recipient = '<ENTER VALUE>';
require('vendor/autoload.php');
$rcsdk = new RingCentral\SDK\SDK(getenv('clientId'), getenv('clientSecret'), getenv('serverURL'));
$platform = $rcsdk->platform();
$platform->login(getenv('username'), getenv('extension'), getenv('password'));
$request = $rcsdk->createMultipartBuilder()
->setBody(array(
'to' => array(array('phoneNumber' => $recipient)),
'faxResolution' => 'High',
))
->add(fopen('fax.jpg', 'r'))
->request("/restapi/v1.0/account/{$accountId}/extension/{$extensionId}/fax");
$r = $platform->sendRequest($request);
?>

Laravel and Guzzle fopen(): can´t find file uploading to an server

I´m trying to upload an image from my server to another one using an API.
I´ve uploaded to my server using native Storage facade and then, call the Guzzle function to upload the file to the other server.
The problem is that I can´t get the local of the file. Let´s see some code:
public function saveImage(Request $request)
{
// return $request;
$consorciado = Consorciado::where('id', '=', $request->consorciado_id)->first();
$documento = Documento::where('doc_id', '=', $request->id)->first();
$documento = new Documento();
$image = request()->file('f');
$documento->consorciado_id = $consorciado->id;
$documento->doc_id = $request->id;
$documento->tipo = $request->tipo;
$documento->remark = $request->remark;
$documento->idTematica = $request->idTematica;
$documento->field1 = $request->field1;
$documento->field2 = $request->field2;
$documento->field3 = $request->field3;
$documento->field4 = $request->field4;
$documento->field5 = $request->field5;
$filename = $consorciado->id . "_" . $documento->doc_id . "." . $image->getClientOriginalExtension();
$documento->nome = $filename;
// dd($doc);
// $file = fopen(Storage::disk('local') . '/' . file_get_contents($image), 'r');
// dd($file);
$client = new Client([
'base_uri' => 'http://gedocflex.com.br:8003/api/file',
]);
$response = $client->request('POST', 'http://gedocflex.com.br:8003/api/file', [
'multipart' => [
[
'name' => 'idTematica',
'contents' => '201'
],
[
'name' => 'f',
// 'contents' => $filename, file_get_contents($image)
'contents' => fopen('/' . $filename, file_get_contents($image), 'w+')
],
[
'name' => 'field1',
'contents' => '132.626.688-85'
],
[
'name' => 'field2',
'contents' => '7758'
],
[
'name' => 'field3',
'contents' => '404'
],
[
'name' => 'field4',
'contents' => '0'
],
[
'name' => 'field5',
'contents' => 'Marcello Dantas Correia'
],
[
'name' => 'remark',
'contents' => 'Enviando do meu servidor para o GED'
],
]
]);
return $response;
Storage::disk('local')->put('public/' . $filename, file_get_contents($image), 'public');
$documento->save(); //salva no meu banco
}
I´m using php artisan storage:link and the error is:
{message: "fopen(/1_1.jpeg): failed to open stream: No such file or directory",…}
exception: "ErrorException"
file: "/Users/marcellopato/Sites/contemplado/app/Http/Controllers/DocumentoController.php"
line: 234
message: "fopen(/1_1.jpeg): failed to open stream: No such file or directory"
trace: [{function: "handleError", class: "Illuminate\Foundation\Bootstrap\HandleExceptions", type: "->"},…]
As you can see, I get the name of the file, but not its path.
What I am doing wrong?
Anyone?
Thanks in advance!

How to view image and pdf files preview in yii2 kartik multiple file upload in update form

Here below is the kartik file input widget in update_form.
echo FileInput::widget(
[
'name' => 'BriefRequirements[requirement_value][]',
'attribute' => 'assets_file',
'id' => 'assets_file',
'options' => ['multiple' => true],
'pluginOptions' => [
'overwriteInitial' => false,
'initialPreview' => $image_url,
'deleteUrl' => ' site/delete',
'initialPreviewAsData' => true,
'initialPreviewFileType' => 'image' //'pdf'
]
]
);
below is multiple image loading code,
foreach ($modelRequirements as $req) {
$image_url[] = Yii::$app->request->baseUrl
. '/theme/business_campaign_files/'
. $req['requirement_value'];
}
I need help with my two questions:
Need to show all selected format files like image, pdf, doc etc [I tried to like 'initialPreviewFileType'=>'any'] not working.
I want to pass the selected image id to action to delete the image? - 'deleteUrl' => ' site/delete','id'=>12, <-- like this.
In the below code i got the result for my two questions.
$initializeConfig = [];
$initializeConfig1 = [];
if ($modelRequirements) {
foreach ($modelRequirements as $req) {
$extension = substr(
$req['requirement_value'],
strrpos($req['requirement_value'], '.') + 1
);
$image_url[] = Yii::$app->request->baseUrl
. '/theme/business_campaign_files/'
. $req['requirement_value'];
$initializeConfig1['url'] = Url::toRoute('delete-requirement');
$initializeConfig1['key'] = $req['id'];
$initializeConfig1['type'] = $type;
array_push($initializeConfig, $initializeConfig1);
}
}
In the above code i got the result for my two questions.
For delete -> mentioned url I wrote the delete function, also through key parameter I passed the id.
For view all the extension files u have to send like "type" $initializeConfig1['type'] = $type; in the type variable i am getting the image extension based on the extension i am setting the format of the file like[pdf,xlsx,image].
easyOne
Various methods to manage your preview. The following features are demonstrated in this example:
For Single Image you can make it Multiple Same as
$files = array();
$files['initialPreview'] = Url::base(TRUE) . '/' . $uploadurl . $newFileName;
$files['initialPreviewAsData'] = true;
//FOR PDF
if ($fieldtype == 'pdf') {
$files['initialPreviewConfig'][] = array('type' => 'pdf', 'key' => $newFileName);
} else {
//FOR IMAGES
$files['initialPreviewConfig']['key'] = $newFileName;
}
$files['namefile'] = $newFileName;
JSON Response :
{
"initialPreview": "http://localhost/yii2/uploads/project/brochure/fileone.pdf",
"initialPreviewAsData": true,
"initialPreviewConfig": [
{
"type": "pdf",
"key": "fileone.pdf"
}
],
"namefile": "fileone.pdf"
}

Can't write image data laravel 5 Intervention

This question have been asked many times in SO, but still I cannot figure it out why is this not working for me.
I am working on E-Commerce Laravel Project.
The issue is that, when the admin uploads the image file of the product, get the error of:
Can't write image data to path
(http://example.com/ankur/images/uploads/products/img-newprod-540-350-350.jpg)
Here's the controller snippet of storing the image and related entries:
public function storeGeneral(Request $request)
{
$this->validate($request, [
'code' => 'required|alpha_dash|unique:products',
'name' => 'required',
'description' => 'string',
'details' => 'string',
'price' => 'required|regex:/^\d*(\.\d{2})?$/',
'tax_amount' => 'required|regex:/^\d*(\.\d{2})?$/',
'net_price' => 'required|regex:/^\d*(\.\d{2})?$/',
'weight' => 'required|integer',
'image_file' => 'image|mimes:jpeg,jpg,JPG'
]);
if ($request->ajax() ) {
if ($request->file('image_file' ) ) {
$request['img_code'] = 'img-' . $request->get('code' );
$product = Product::create($request->all() );
$product->categories()->attach($request->input('category_id') );
Session::put('product_last_inserted_id', $product->id);
$mgCode = DB::table('products')->latest()->limit(1)->pluck('img_code');
$imageType = [
'product' => [
'height' => 350,
'width' => 350
],
'carousel' => [
'height' => 163,
'width' => 163
],
'cart' => [
'height' => 64,
'width' => 64
]
];
foreach($imageType as $key => $value)
{
$fileName = Safeurl::make($mgCode );
$image = Image::make($request->file('image_file' ) );
//$path = public_path( 'images/uploads/products/' );
$path = url('/images/uploads/products/');
if ($key == 'product') {
$image->resize($value['width'], $value['height'] );
$image->save($path.'/'.$fileName."-". $value['width'] ."-".$value['height'] .".jpg", 100 );
} else if ($key == 'carousel' ) {
$image->resize($value['width'], $value['height'] );
$image->save($path.'/'.$fileName."-". $value['width'] ."-".$value['height'] .".jpg", 100 );
} else if ($key == 'cart' ) {
$image->resize($value['width'], $value['height'] );
$image->save($path.'/'.$fileName."-". $value['width'] ."-".$value['height'] .".jpg", 100 );
}
}
} else {
$product = Product::create($request->all() );
Session::put('product_last_inserted_id', $product->id);
}
return response(['status' => 'success', 'msg' => 'The product has been added successfully.']);
}
return response(['status' => 'failed', 'msg' => 'The product could not be added successfully.']);
}
The folder permission that I have is 0777 for the images directory and it's sub directories.
But still I get the above mentioned error exception.
EDIT 1:
This is the folder structure in my hosting account file manager which is inside the public_html directory:
Can anybody help me out with this.
Thanks in advance.
I have somehow figured it out.
Instead of using url() or base_path(), I used public_path().
Code that I used:
$path = public_path('../../public_html/ankur/images/uploads/products');
Worked like a charm.
You are trying to save image using url. Instead of url try following
$path = base_path().'/images/uploads/products';
You can not save the image using http path. You have to use base_path() or manual type full server directory path /home/webtuningtechnology/public_html/images/ like this

Categories