Code On
Code On

Reputation: 233

Laravel : How to send image or file to API

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

Upvotes: 13

Views: 42225

Answers (2)

Touhid
Touhid

Reputation: 1686

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

Upvotes: 10

Filip Koblański
Filip Koblański

Reputation: 10008

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

Upvotes: 4

Related Questions