Laravel : How to send image or file to API

Code On picture Code On · Oct 19, 2016 · Viewed 20.5k times · Source

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); 

Answer

Touhid picture Touhid · May 19, 2019

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