How to Create and Use BLOB URLs with PHP and MySQL

While BLOB URLs are primarily created and managed using JavaScript in the browser, PHP can play an important role in handling files on the server side. This tutorial will demonstrate how to use PHP to upload, store, and retrieve files, and then use JavaScript to generate and use BLOB URLs for these files in the browser.


Step 1: Set Up a MySQL Database to Store Files

Create a MySQL table to store the uploaded files.


CREATE TABLE files (

    id INT AUTO_INCREMENT PRIMARY KEY,

    file_name VARCHAR(255) NOT NULL,

    file_data BLOB NOT NULL

);


Step 2: Build a File Upload System in PHP

Create a PHP script to handle file uploads and store them in the database.


upload.php

<?php

// Database connection

$host = 'localhost';

$dbname = 'your_database';

$username = 'root';

$password = '';

$conn = new mysqli($host, $username, $password, $dbname);


if ($conn->connect_error) {

    die("Connection failed: " . $conn->connect_error);

}


// File upload logic

if (isset($_FILES['file'])) {

    $fileName = $_FILES['file']['name'];

    $fileData = file_get_contents($_FILES['file']['tmp_name']);


    // Prepare and execute SQL statement

    $stmt = $conn->prepare("INSERT INTO files (file_name, file_data) VALUES (?, ?)");

    $stmt->bind_param("sb", $fileName, $fileData);

    $stmt->send_long_data(1, $fileData); // Send BLOB data

    $stmt->execute();


    echo "File uploaded successfully.";

}

?>


<!-- HTML form for file upload -->

<form action="upload.php" method="post" enctype="multipart/form-data">

    <input type="file" name="file" required>

    <button type="submit">Upload</button>

</form>


Step 3: Retrieve Files from the Database

Create a PHP script to retrieve the file data and send it to the client.


fetch_file.php


<?php

// Database connection

$host = 'localhost';

$dbname = 'your_database';

$username = 'root';

$password = '';

$conn = new mysqli($host, $username, $password, $dbname);


if ($conn->connect_error) {

    die("Connection failed: " . $conn->connect_error);

}


// Retrieve file data by ID

$fileId = $_GET['id'];

$stmt = $conn->prepare("SELECT file_name, file_data FROM files WHERE id = ?");

$stmt->bind_param("i", $fileId);

$stmt->execute();

$stmt->store_result();

$stmt->bind_result($fileName, $fileData);

$stmt->fetch();


// Send file data as a response

header("Content-Type: application/octet-stream");

header("Content-Disposition: inline; filename=\"$fileName\"");

echo $fileData;

?>


Step 4: Generate BLOB URLs in JavaScript

Use JavaScript to fetch the file data and generate a BLOB URL.


blob_url_example.php


<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Generate BLOB URL</title>

</head>

<body>

    <button id="download-btn">Download File</button>

    <script>

        // Fetch file data and create a BLOB URL

        document.getElementById('download-btn').addEventListener('click', async () => {

            const fileId = 1; // Replace with the ID of the file to download

            const response = await fetch(`fetch_file.php?id=${fileId}`);

            const blob = await response.blob();


            // Create a BLOB URL

            const blobUrl = URL.createObjectURL(blob);

            console.log('BLOB URL:', blobUrl);


            // Create a link to download the file

            const link = document.createElement('a');

            link.href = blobUrl;

            link.download = 'downloaded_file'; // Replace with the desired file name

            document.body.appendChild(link);

            link.click();

            document.body.removeChild(link);


            // Revoke the BLOB URL to free up memory

            URL.revokeObjectURL(blobUrl);

        });

    </script>

</body>

</html>


Step 5: Testing the Application

Run the upload.php script to upload files.

Use the fetch_file.php script to retrieve file data by ID.

Open the blob_url_example.php script to generate and use BLOB URLs for downloading the files.

Best Practices

Sanitize File Inputs: Always validate file types and sizes to prevent malicious uploads.

Manage Memory: Use URL.revokeObjectURL() after finishing with a BLOB URL to free up resources.

Use Proper MIME Types: Ensure the Content-Type header matches the file type in fetch_file.php.

This approach combines the power of PHP for server-side file management with JavaScript's capability to create and manage BLOB URLs for client-side functionality. Hope this is helpful, and I apologize if there are any inaccuracies in the information provided.

Comments

Popular posts from this blog

Integrating PHP with Message Queues RabbitMQ Kafka

FastAPI and UVLoop: The Perfect Pair for Asynchronous API Development

Konfigurasi dan Instalasi PostgreSQL Secara Lengkap di Windows Linux dan MacOS