Laravel : How to send image or file to API

29,084

Solution 1

Below simple code worked for me to upload file with postman (API):

This code has some validation also.

If anyone needs just put below code to your controller.

From postman: use POST method, select body and form-data, select file and use image as key after that select file from value which you need to upload.

public function uploadTest(Request $request) {

    if(!$request->hasFile('image')) {
        return response()->json(['upload_file_not_found'], 400);
    }
    $file = $request->file('image');
    if(!$file->isValid()) {
        return response()->json(['invalid_file_upload'], 400);
    }
    $path = public_path() . '/uploads/images/store/';
    $file->move($path, $file->getClientOriginalName());
    return response()->json(compact('path'));
 }

Solution 2

Well the true is that you won't be able to do it without sending it by post from form.

The alternative is to send the remote url source and download it in the API like this:

if ($request->has('imageUrl')) {

    $imgUrl = $request->get('imageUrl');
    $fileName = array_pop(explode(DIRECTORY_SEPARATOR, $imgUrl));
    $image = file_get_contents($imgUrl);

    $destinationPath = base_path() . '/public/uploads/images/product/' . $fileName;

    file_put_contents($destinationPath, $image);
    $attributes['image'] = $fileName;
}
Share:
29,084
Code On
Author by

Code On

Updated on July 22, 2022

Comments

  • Code On
    Code On almost 2 years

    I have an API (created by Lumen) to save an image or file from client side.

    this is my API code

    if ($request->hasFile('image')) {
        $image = $request->file('image');
    
        $fileName = $image->getClientOriginalName();
        $destinationPath = base_path() . '/public/uploads/images/product/' . $fileName;
        $image->move($destinationPath, $fileName);
    
        $attributes['image'] = $fileName;
    }
    

    I already try the API in postman, and everything went well, image sucessfully uploaded.

    What's the best practice to send image from client side (call the API), and save the image in the API project ? because my code isn't working..

    This is my code when try to receive image file in client side, and then call the API.

    if ($request->hasFile('image')) {
        $params['image'] = $request->file('image');
    }
    
    $data['results'] = callAPI($method, $uri, $params);