Laravel: How to send image or file to API

I have an API (created by Lumen) to save an image or file from the 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 tried the API in the postman, and everything went well, the image successfully uploaded.

What is the best way to send an image from the client side (call the API) and save the image in the API project? because my code is not working.

This is my code when you try to get the image file on the client side and then call the API.

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

Well, it’s true that you cannot do this without sending it by mail from the form.

An alternative is to send the remote URL source and load it into the API as follows:

 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; } 
+3
source

The following simple code worked for me to download a postman file (API):

This code also has some validation.

If someone needs to just put the code below for your controller.

From the postman: use the POST method, select body and form-data, select the file and use the image as the key, then select the file from the value 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')); } 
0
source

Source: https://habr.com/ru/post/1258462/


All Articles