pyrogrammer
pyrogrammer

Reputation: 560

Unable to send file using laravel http client to the api

So I have made an api in laravel. Here is the code in

ApiController.php

This is the api function

public function apiFileReceive(Request $request){
      $file=$request->file('filename');
      $filename = $file->getClientOriginalName();
      $extension = $file->getClientOriginalExtension();
      $tempPath = $file->getRealPath();
      $fileSize = $file->getSize();
      $mimeType = $file->getMimeType();
      return response(['filename'=>$filename, 'extension'=>$extension,'fileSize'=>$fileSize,'mimetype'=>$mimeType,'file'=>$request->file('filename')],200);
    }

HomeController.php

This is the code from where I am calling the api.

public function sendFileToApi(Request $request){
        if($request->admission_import!=null){
            $file = $request->file('admission_import');
            $filename = $file->getClientOriginalName();
            $response=Http::attach('filename',$request->file('admission_import'),$filename)->post('localhost/address_of_api');
            
            $val=$response->json();
            dd($val);
        }
    }

The problem is when I am trying to access the file in ApiController's apiFileReceive() function. I am unable to access the file. dd($val) shows this After dd($val)

The file is null. Can somebody tell me what I'm missing.

Upvotes: 1

Views: 695

Answers (1)

pyrogrammer
pyrogrammer

Reputation: 560

This is the solution for this-: In Homecontroller.php

            $file = $request->file('admission_import');
            $filename = $file->getClientOriginalName();
            $response=Http::attach('admission_import',file_get_contents($file->getRealPath()),$filename)->post(''localhost/address_of_api'');
            
            $val=$response->json();
            dd($val);

In ApiController.php change this line.

$file=$request->file('filename'); To $file=$request->file('admission_import');

And it is good to go.

Upvotes: 1

Related Questions