Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); 
like image 480
Code On Avatar asked Oct 19 '16 10:10

Code On


People also ask

How do I send a picture to API?

Option 1: Direct File Upload , From this method you can select form-data and set the type to file. Then select an image file by clicking on the button shown in the value column. The content type is automatically detect by postman but if you want you can set it with a relevant MIME type.


1 Answers

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'));
 }
like image 190
Touhid Avatar answered Sep 22 '22 00:09

Touhid