Laravel API File Uploads


Uploading files to a Laravel API using JavaScript involves a few steps: setting up the API to handle file uploads, creating the frontend to allow file selection, and using the Fetch API to send the file to the server. Here’s a detailed guide on how to achieve this.

Step-by-Step Guide to File Uploads

1. Set Up the Laravel API

First, you need to create a route and controller method to handle the file upload.

Define the Route:

In routes/api.php, add a route for handling file uploads:

use App\Http\Controllers\FileUploadController; Route::post('/upload', [FileUploadController::class, 'upload']);

Create the Controller Method:

Next, create a controller to handle the file upload. You can create a controller using the artisan command:

php artisan make:controller FileUploadController

Then, implement the upload method in FileUploadController.php:

namespace App\Http\Controllers; use Illuminate\Http\Request; class FileUploadController extends Controller { public function upload(Request $request) { // Validate the incoming request for file $request->validate([ 'file' => 'required|file|mimes:jpg,png,pdf|max:2048', // Limit file types and size ]); // Store the file if ($request->file('file')) { $path = $request->file('file')->store('uploads'); // Store in 'storage/app/uploads' return response()->json(['path' => $path], 201); // Return path of uploaded file } return response()->json(['message' => 'File upload failed.'], 400); // Return error message } }

2. Create the Frontend with JavaScript

You will create a simple form to allow users to select a file and upload it to the Laravel API.

HTML Form:

Here’s an example HTML form for file uploads:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>File Upload</title> </head> <body> <h1>Upload File</h1> <form id="file-upload-form"> <input type="file" id="file" name="file" required><br> <button type="submit">Upload</button> </form> <div id="response-message"></div> <script src="app.js"></script> <!-- Link to your JavaScript file --> </body> </html>

JavaScript Fetch Request:

In a file named app.js, implement the JavaScript to handle the form submission and make the POST request to upload the file:

document.addEventListener('DOMContentLoaded', () => { const form = document.getElementById('file-upload-form'); const responseMessage = document.getElementById('response-message'); form.addEventListener('submit', (event) => { event.preventDefault(); // Prevent the default form submission const formData = new FormData(); // Create FormData object const fileInput = document.getElementById('file'); formData.append('file', fileInput.files[0]); // Append the selected file // Make a POST request to the API fetch('http://your-app.test/api/upload', { // Replace with your API URL method: 'POST', body: formData // Send FormData as the body }) .then(response => { if (!response.ok) { throw new Error('Network response was not ok ' + response.statusText); } return response.json(); // Parse JSON response }) .then(data => { responseMessage.textContent = `File uploaded successfully: ${data.path}`; // Display success message }) .catch(error => { console.error('There was a problem with the fetch operation:', error); responseMessage.textContent = 'Error: ' + error.message; // Display error message }); }); });

3. Handling CORS (Cross-Origin Resource Sharing)

If your Laravel API and frontend are running on different origins (different domains or ports), you might encounter CORS issues. To enable CORS in Laravel, you can use the Laravel CORS package.

You can install it via Composer if it isn't already included in your project:

composer require fruitcake/laravel-cors

After installing, configure the CORS settings in config/cors.php to allow requests from your frontend's origin.

4. Configuring File Storage

Ensure that your filesystems.php configuration is set up correctly. The default storage disk is set to local, which stores files in the storage/app directory. You might want to create a symbolic link to make the uploads accessible from the web:

php artisan storage:link

This command will create a symbolic link from public/storage to storage/app/public, making files accessible via the public URL.

Summary

In this guide, you learned how to:

  • Set up a Laravel API endpoint to handle file uploads.
  • Create a simple HTML form for selecting and uploading files.
  • Use JavaScript's Fetch API to send the file to the Laravel API and handle the response.

This process allows users to upload files easily and provides dynamic feedback based on the upload's success or failure.