Laravel - File Uploading

Laravel - File Uploading

Step 1: Create a View for File Upload

Create a new view file resources/views/uploadfile.blade.php. In this file, we will create a simple form to allow users to upload a file.

@extends('layouts.app') @section('content') <div class="container"> <h2>Upload File</h2> <!-- Form for file upload --> {!! Form::open(['url' => '/uploadfile', 'files' => true]) !!} <div class="form-group"> <label for="image">Select a file to upload:</label> {!! Form::file('image', ['class' => 'form-control']) !!} </div> {!! Form::submit('Upload File', ['class' => 'btn btn-primary']) !!} {!! Form::close() !!} </div> @endsection

Step 2: Create a Controller to Handle File Uploads

Run the following Artisan command to create a new controller:

php artisan make:controller UploadFileController --plain

This will generate a controller UploadFileController.php in the app/Http/Controllers directory. Now, edit this file to handle file uploads.

namespace App\Http\Controllers; use Illuminate\Http\Request; class UploadFileController extends Controller { // Show the file upload form public function index() { return view('uploadfile'); } // Handle the file upload public function showUploadFile(Request $request) { // Get the uploaded file $file = $request->file('image'); // Check if the file is valid if ($file->isValid()) { // Display file details (for debugging) echo 'File Name: ' . $file->getClientOriginalName() . '<br>'; echo 'File Extension: ' . $file->getClientOriginalExtension() . '<br>'; echo 'File Real Path: ' . $file->getRealPath() . '<br>'; echo 'File Size: ' . $file->getSize() . '<br>'; echo 'File Mime Type: ' . $file->getMimeType() . '<br>'; // Define the destination path where the file will be stored $destinationPath = 'uploads'; // Move the file to the destination path $file->move($destinationPath, $file->getClientOriginalName()); // Optionally, you can save file information in a database here // For example: File::create(['name' => $file->getClientOriginalName()]); return redirect('/uploadfile')->with('success', 'File uploaded successfully!'); } return redirect('/uploadfile')->with('error', 'File upload failed!'); } }

Step 3: Define Routes

Now, define the routes to show the form and handle the file upload. Add the following code to your routes/web.php file:

Route::get('/uploadfile', 'UploadFileController@index'); Route::post('/uploadfile', 'UploadFileController@showUploadFile');

Step 4: Create a Directory to Store Files

Make sure to create an uploads directory in your project's public folder to store the uploaded files. You can create the directory manually, or Laravel will create it automatically when you move a file. However, ensure the directory is writable by your web server.

mkdir public/uploads

Ensure the correct permissions for the directory:

chmod -R 775 public/uploads

Step 5: Test the File Upload

To test the file upload functionality, visit the following URL in your browser:

http://localhost:8000/uploadfile

You should see a file upload form. When you select a file and submit the form, the file will be uploaded, and you should see the file details printed on the screen. The file will be saved in the public/uploads directory.

Step 6: Add Success/Error Messages (Optional)

To enhance the user experience, you can add success and error messages. In the uploadfile.blade.php view, add the following code to display messages:

@if (session('success')) <div class="alert alert-success"> {{ session('success') }} </div> @endif @if (session('error')) <div class="alert alert-danger"> {{ session('error') }} </div> @endif

This will display a success message after a successful upload and an error message if something goes wrong.

Conclusion

With these steps, you now have a working file upload functionality in Laravel. The user can upload a file via a form, and the file will be stored on the server in the public/uploads directory.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close