Sending file to api endpoint using guzzle and laravel - php

I'm trying to use guzzle to send a file to an api endpoint. WebsiteA (laravel) will send a file input to WebsiteB (laravel). The problem is, I'm getting a tmp path only in WebisteB when i check the request and not the whole file. I need to store the file in WebsiteB.
If i dd($request->file('file')) on WebsiteA it returns image below.
WebsiteA
public function postContent(Request $request) {
if($request->file){
$response = $this->guzzleClient()->post($this->archiving->url . config('archiving.api_post_file_content'),
[
'multipart' => [
[
'name' => 'file',
'contents' => $request->file('file'),
],
],
]
);
return $response->getBody();
}else{
return 'no file';
}
}
WebsiteB
public function storeContentFile(Request $request){
return $request->all(); //returns -> file: "C:\xampp\tmp\phpFEA3.tmp"
/* if($request->file){
$uploadedFiles=$request->file('file');
$file_name = time().'.'.$uploadedFiles->getClientOriginalName();
$uploadedFiles->move('media/content/', $file_name);
}
*/
//getting error getClientOriginalName() on string
}

Related

How to POST data on database using Postman with laravel 9

I try to POST data to database with "form-data" on "postman" with Laravel 9, and I try to return the data to JSON.
This is my controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\M_Barang;
class Utama extends Controller
{
public function index() {
return view('Utama');
}
public function store(Request $request) {
$this->validate($request, [
'file' => 'required|max:2048'
]);
$file = $request->file('file');
$nama_file = time()."_".$file->getClientOriginalName();
$tujuan_upload = 'data_file';
if ($file->move($tujuan_upload,$nama_file)) {
$data = M_Barang::create([
'nama_produk' => $request->nama_produk,
'harga' => $request->harga,
'gambar' => $nama_file
]);
$res['message'] = "succsess!";
$res['values'] = $data;
return response($res);
}
}
}
I get the following result:
This is my expected result:
You need to send data from raw section in JSON Format, and try to send your image in base64 format (because its very convenient way to store a image into file system via the API).
Example:{"profile_pic":"data:image/png;base64,iVBORw0KGgoAAAANSUh (base64 image string)"}
you can convert base64 image here https://www.base64-image.de/
and in Android and iOS has some libraries for converting image to base 64 while sending data to API
Welcome in Advance.
In Postman's headers section, you have to set Accept and content-type to application/json:
Image

Is there a way to upload Images using Laravel Jobs

I am trying to upload image in laravel jobs but i keep getting this error "Serialization of 'Illuminate\\Http\\UploadedFile' is not allowed"
In my controller i try to save the image to wasabi cloud and then passing it to the job by doing this
public function store(ThreadRequest $request)
{
$imageName = time().'.'.$request->attachment->extension();
$request->attachment->storeAs('public/attachments', $imageName, 'wasabi');
$this->dispatch(CreateThread::fromRequest($request, $imageName));
return redirect()->route('threads.index');
}
And then in my job i accept $imageName as attachment and did this
public function handle(): Thread
{
$thread = new Thread([
'title' => $this->title,
'body' => Purifier::clean($this->body),
'category_id' => $this->category,
]);
$thread->authoredBy($this->author);
$thread->save();
return $thread;
}
}
I tried passing the image from my controller to my job, although i know you need to save the image temp and pass it to laravel job but that's where i am confused.
Any help would be appreciated.

405 Method not allowed with Guzzle POST request in PHP

I'm stuck since several hours on a the consumption of a locale API (which I created) with PHP and Guzzle on a laravel project (8.7).
I've created deux differents laravel projects on the same local server. One is providing some API routes and the second one consume it.
On the first project (which providing APIs) I've created several routes to create, read, update and delete datas from my database.
To access this API routes we need to first consume an API route called "login". This one handle the creation of a token according to a given couple email/password.
This token is needed to call all the others API routes.
The /api/login API is a POST request with email and password datas.
/api/login route declaration : (I would like to specify that this route is into the api.php file into my laravel project so the corresponding url is : http://xxx.xxx.x.xxx/site/public/api/login)
Route::post('login',[AdminController::class,'index']);
Index method for /api/login :
function index(Request $request)
{
if(!($request->ip() == "xxx.xxx.x.xxx")) {
Log::alert('Ip ' . $request->ip() . ' a tenté de se connecter à l\'Api');
return response([
'message' => ['Authentification failed']
], 403);
}
$admin = Admin::where('email', $request->email)->first();
if (!$admin || !Hash::check($request->password, $admin->password)) {
return response([
'message' => ['Email-password couple is incorrect']
], 403);
}
$token = $admin->createToken('my-app-token')->plainTextToken;
$response = [
'admin' => $admin,
'token' => $token
];
return response($response, 201);
}
In my second project I'm using Guzzle to consome my APIs.
/articles route declaration : (http://xxx.xxx.x.xxx/backoffice/public/api/login)
Route::prefix('articles')->group(function () {
Route::any('/', [ArticlesController::class, 'index'])->name('articles-index');
});
Index method for /articles :
public function index() {
$client = new \GuzzleHttp\Client();
$request = $client->request('POST', 'http://xxx.xxx.x.xxx/site/public/api/login/', [
'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'],
'form_params' => [
'email' => 'test#gmail.com',
'password' => 'dAvG454aquysla4'
],
'debug' => true,
]);
$response = $request->getBody()->getContents();
return view('articles.index', [
]);
}
I'm getting this error :
GuzzleHttp\Exception\ClientException Client error: 'POST http://xxx.xxx.x.xxx/site/public/api/login/' resulted in a '405 Method Not Allowed' response: <!doctype html> <html class="theme-light"> <!-- Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException: Th (truncated...)
I don't understand where is my mistake...
The /api/login is correctly define in POST http method and works perfectly with Insomnia.
Does anyone have an idea or will be able to help me using Guzzle? It's the first time I'm using it.
I'm used to consume API with fetch (ajax) in JS.
Thanks ;)

Laravel 5.4 file upload validation fails for python files

I'm trying to figure out what is wrong with my validation, but I'm not sure.
I have created a file upload that uploads the file to S3. Works fine except when I need to validate python files.
In my FileUploadController.php I have a store(FileStoreRequest $request) method that handles the upload. I added the $validatedData = $request->validate(); in it and it works.
I have also added the mimes.php in config folder with the following:
<?php
return [
'zip' => array('application/x-zip', 'application/zip', 'application/x-zip-compressed'),
'py' => array('text/plain', 'application/x-python' , 'application/octet-stream, application/x-python-code, text/x-python-script', 'text/x-python'),
];
And the rules() method inside my FileStoreRequest class is
public function rules()
{
return [
'preprocessor' => 'mimes:py',
];
}
Any time I try to upload the python file I get the error
The preprocessor must be a file of type: py.
When I remove the mimes check from the rules() it passes.
The rules work, because I tested it on another view for zip file upload.
Any ideas what could be wrong?
You can create custom validation like:
$input = $request->all();
if (isset($input["preprocessor"]) && !empty($input["preprocessor"])) {
$filesource = $input["preprocessor"];
$fileExtension = $filesource->getClientOriginalExtension();
$input["ext"] = $fileExtension;
}
$rules = array(
'ext' => 'nullable|in:py',
);

Laravel displaying base64 image

How can I send e-mail with attached image if I receive the data in base64 format?
Here is mail template:
<h1>You got mail from - {{$user->name}}</h1>
<h2>Date:</h2>
<p>{{$post->created_at}}</p>
<h2>Message:</h2>
<p>{{$post->body}}</p>
<img src="data:image/png;base64, {{$image}}">
<div>
</div>
And the logic:
public function createPost()
{
$user = JWTAuth::toUser();
$user->posts()->create(['user_id' => $user->id, 'body' => Input::get('comment.body')]);
Mail::send('mail.template', [
'image' => Input::get('image'),
'user' => $user,
'post' => Post::where('user_id', $user->id)->get()->last(),
], function ($m) use ($user) {
$m->from('xyz#app.com', 'XYZ');
$m->to('xyz#gmail.com', $user->name)->subject('Subject');
});
}
From this I only get mail with full base64 string...img tag gets ignored
Attachments
To add attachments to an email, use the attach method within the
mailable class' build method. The attach method accepts the full path
to the file as its first argument:
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('emails.orders.shipped')
->attach('/path/to/file');
}
More information here (for Laravel 5.3).
I hope, it will be helpful.
The solution I came up with is to save the image first in order to attach it as Viktor suggested although I don't have Laravel 5.3. so the method is somehow different.
User may or may not send the picture, so the method is as follows:
$destinationPath = null;
if($request->has('image')){
// save received base64 image
$destinationPath = public_path() . '/uploads/sent/uploaded' . time() . '.jpg';
$base64 = $request->get('image');
file_put_contents($destinationPath, base64_decode($base64));
}
And then attach the saved image to the mail:
Mail::send('mail.template', [
'user' => $user,
'post' => Post::where('user_id', $user->id)->get()->last(),
], function ($m) use ($user) {
$m->from('xyz#app.com', 'XYZ');
$m->to('xyz#gmail.com', $user->name)->subject('Subject');
if($request->has('image')){
$m->attach($destinationPath);
}
});
The mail template:
<h1>You got mail from - {{$user->name}}</h1>
<h2>Date:</h2>
<p>{{$post->created_at}}</p>
<h2>Message:</h2>
<p>{{$post->body}}</p>

Categories