Ad

How To Upload Image To Server Using Php Laravel?

- 1 answer

I've been trying to write an api to upload image to server ,but all in vain. I'm using the laravel framework .And tried this example but it is not working.

Also while testing the api from POSTMAN ,I have passed mutlipart/form-data in the Headers.And in the Body tab selected form-data, added key = image, changed it Text to File and added an image.But when I test the api , don't know why but the image request is empty.

Maybe I might be passing something wrong in POSTMAN or there might be something wrong in my code,please do help me.

Here's my api code

public function upload(Request $request){

if ($request->hasFile('image')) {
   $image = $request->file('image');
   $name = md5(time().uniqid()).".png";
   $destinationPath = base_path() . '/public/uploads/images/' . $name;

   move_uploaded_file($name, $destinationPath);

   return response()->json(['title'=>"image is uploaded"]);
   }

}

And my controller code :

Route::post('uploadImage','[email protected]');

Screenshot of the postman request.Please tell me if I'm passing something wrong in header or body .

enter image description here

Also ,the console shows this error Missing boundary in multipart/form-data POST data in Unknown on line 0

Ad

Answer

You can user core PHP code for file upload. In my laravel project I have used following code to upload file.

if(isset($_FILES["image"]["type"]))
{
  $FILES = $_FILES["image"];
  $upload_dir = storage_path('app/public/document/');

  // create folder if not exists
  if (!file_exists($upload_dir)) {
    mkdir($upload_dir, 0777, true);
  }

  //Send error 
  if ($FILES['error'])
  {
    return response()->json(['error'=>'Invalid file']);
  }

  //Change file name
  $target_file = md5(time().uniqid());
  $imageFileType = pathinfo($FILES["name"],PATHINFO_EXTENSION);
  $target_file = $upload_dir.$target_file.'.'.$imageFileType;

  //Upload file
  if (move_uploaded_file($FILES["tmp_name"], $target_file))
  {
    return response()->json(['success' => 'File uploading successful']);
  }
  else
  {
    return response()->json(['error'=>'Invalid file']);
  }
}else{
 return response()->json(['error'=>'Invalid file']);
}

Below is the screenshot when I print $_FILES at the beginning of the function enter image description here

Ad
source: stackoverflow.com
Ad