12

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); 
4
  • Are you want to save an image? Oct 19, 2016 at 11:10
  • yes, send image to API, and save it into API public folder
    – Code On
    Oct 19, 2016 at 11:16
  • one option is encode the file in base 64 and send via POST. But you need to change your 'server' code source
    – cmnardi
    Oct 19, 2016 at 11:19
  • For that, you need to decode it using base64 and then you were able to save it in public folder. Oct 19, 2016 at 11:19

2 Answers 2

9

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.