Langsung ke konten utama

The easy way to upload file using Laravel Framework for more secure to prevent injection attact

Laravel is a popular PHP web application framework that provides developers with a set of tools and functionalities to build high-quality, scalable web applications quickly. One of the most common tasks that web applications need to perform is to allow users to upload files to the server and store them in a specific folder, and also read and download those files. In this article, we will discuss how to upload and store files using Laravel Framework and read/download those files.

Step 1: Create a Form

To upload a file, you need to create an HTML form that allows the user to select a file to upload. The following code shows an example of a simple form that allows the user to select a file and submit it to the server:

<form action="{{ route('file.upload') }}" method="POST" enctype="multipart/form-data">
    @csrf
    <input type="file" name="file" />
    <button type="submit">Upload File</button>
</form>

The above code creates an HTML form with an input element of type "file". The "enctype" attribute of the form is set to "multipart/form-data", which is necessary when uploading files. The "csrf" token is added for security purposes.

Step 2: Create a Route

Next, you need to create a route that maps to the controller method that will handle the file upload. In this example, we will create a route that maps to the "uploadFile" method of the "FileController". Add the following code to your "routes/web.php" file:

Route::post('/file/upload', [FileController::class, 'uploadFile'])->name('file.upload');

Step 3: Create a Controller

Now you need to create a controller method that will handle the file upload. In this example, we will create a "FileController" with a "uploadFile" method that will handle the file upload. Add the following code to your "app/Http/Controllers/FileController.php" file: 

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class FileController extends Controller
{
    public function uploadFile(Request $request)
    {
        $file = $request->file('file');
        
        if($file){
            $filename = time().'_'.$file->getClientOriginalName();
            Storage::disk('public')->put($filename, file_get_contents($file));
            return redirect()->back()->with(['success' => 'File uploaded successfully.']);
        }
        
        return redirect()->back()->with(['error' => 'Please select a file.']);
    }
    
    public function readDownloadFile($filename)
    {
        $path = Storage::disk('public')->path($filename);
        
        if(!Storage::disk('public')->exists($filename)){
            return redirect()->back()->with(['error' => 'File not found.']);
        }
        
        $content = file_get_contents($path);
        
        return response($content)
            ->header('Content-Type', mime_content_type($path))
            ->header('Content-Disposition', 'attachment; filename="'.$filename.'"');
    }
}

The above code creates a controller class called "FileController" with a method called "uploadFile" that handles the file upload and "readDownloadFile" method that reads and downloads the file. The "uploadFile" method receives a "Request" object that contains the uploaded file. The method checks if a file was uploaded and if so, it generates a unique filename, stores the file in the "public" disk using the "Storage" facade, and redirects back with a success message. If no file was uploaded, it redirects back with an error message.

the readDownloadFile method in the FileController class is used to read and download a file that has already been uploaded and stored in the server's file system.

The method accepts the $filename parameter, which is the name of the file that needs to be read and downloaded. It first retrieves the full path of the file using the path method of the Storage facade. If the file does not exist in the public disk, it redirects back with an error message.

Then, the method reads the contents of the file using the file_get_contents function and stores it in the $content variable. Finally, it returns a Response object that contains the file's contents and appropriate headers to download the file.

The header method is used to set the "Content-Type" header to the file's MIME type, which is determined using the mime_content_type function. The "Content-Disposition" header is also set to "attachment" to indicate that the file should be downloaded rather than displayed in the browser.

Overall, the readDownloadFile method is a useful utility function for downloading files that have already been uploaded to the server using Laravel.

Happy Coding!!!

Komentar

Postingan populer dari blog ini

Fungsi lain tombol penerima panggilan di headset

Kegunaan tombol yang berada di headset utamanya adalah untuk menerima panggilan dan pause panggilan. Dan headset itu sendiri, kadang juga digunakan untuk mendengarkan music, digunakan bersama saat main game, supaya suara yang dikeluarkan oleh gadget tidak terlalu keras sehingga mengurangi beban gadget. Dengan mengurangi beban gadget, ada beberapa yang beranggapan kalau itu akan menghemat batere.

Apa itu index file seperti index.html, index.php kegunaannya dan bagaimana membuat custom nya

Index file adalah file yang berfungsi sebagai halaman utama atau tampilan pertama dari sebuah website. File ini memiliki nama default yang bervariasi, tergantung pada jenis server dan konfigurasinya, namun beberapa nama default yang umum digunakan adalah index.html, index.php, index.jsp, atau index.asp.

Membersihkan cache dan dalvik-cache menggunakan link2sd

Mungkin banyak yang menanyakan kenapa internalnya selalu berkurang free space nya. Padahal tidak menginstall applikasi baru. Hanya melakukan aktifitas normal. Dan sampai pada waktunya, internal memory low dan tidak bisa menambah aplikasi baru lagi.  Ada kemungkinan file cache dari sebuah aplikasi atau dalvik yang dibuat oleh OS android sudah  mulai membengkak. Sehingga perlu di bersihkan secara manual supaya tersedia penyimpanan kosong yang banyak. Sebelum mengetahui cara membersihkan cache dan dalvik cache, kita kupas sekilas apa itu cache dan dalvik cache. Cache adalah sebuah data file sementara yang di hasilkan oleh sebuah applikasi guna mempercepat pemrosesan dimasa yang akan datang (Cache Wikipedia) .  Dalvik-cache adalah ruang kosong sementara yang di pake oleh java virtual machine untuk menjalankan aplikasi android (Dalvik Wikipedia) .