Upload File or Image on Laravel Through REST API

Last updated on February 28, 2023

In this article, we will learn how to create a REST API that would upload files or images to Laravel. Also, it would validate, rename files and save them into the database.

If you haven’t installed Laravel yet, our article can help you install Laravel fresh application on your local web server.

Let’s start by creating a file controller, below command creates the controller

php artisan make:controller FileController

Next, create a store method and add a request parameter. Request parameter helps to get files from the HTTP request.

public function store(Request $request){

}

Request name can be anything, we can name it anything.

$file = $request->file('file_name');

Here, file_name is the name of the request which is passed into the request’s method that name is file.

$imageName = time().'.'.$file->extension();

Above, we are using the time() function that returns the current time and extension() that returns the extension of the file. These two functions make the unique name of the file.

$imagePath = public_path(). '/files';

Next, we need the path of the directory where the file would be uploaded. Before getting the path we need to create the ‘files’ directory inside the public folder. Laravel’s built-in function public_path() returns the public directory path, so to make a complete path  public_path() should be concatenated with the ‘/files’ string.

$file->move($imagePath, $imageName);

Now, we have enough data for Laravel’s built-in function move() which uploads files on the provided path.

public function store(Request $request)
    {
        $file = $request->file('file');
        $imageName = time().'.'.$file->extension();
        $imagePath = public_path(). '/files';

        $file->move($imagePath, $imageName);

        return response()->json([
            "success" => true,
            "message" => "Image has been uploaded successfully."
        ]);
    }

This method gets the file from the request and then uploads it into the files directory after renaming the file name. Now we need to create a route that would link the store method.

Route::post('save-file', [FileController::class, 'store']);

Conclusion

To upload a file through REST API, you need to get the file from the incoming request through file() method and then put it into move() method as an argument along with the path.


Written by
I am a skilled full-stack developer with extensive experience in creating and deploying large and small-scale applications. My expertise spans front-end and back-end technologies, along with database management and server-side programming.

Share on:

Related Posts

Tags: Laravel,