Home > Enterprise >  Send image to backend as a Blob from Javascript to PHP using Fetch
Send image to backend as a Blob from Javascript to PHP using Fetch

Time:01-28

id is a input where you can upload 1 image.

Basically I'd like for the image to be sent to back-end and be inserted into the DB.

Everything is working except getting the image to backend as a blob and uploading it.

Javascript Code:

const data = {
    first_name: first_name.value,
    last_name: last_name.value,
    email: email.value,
    company: company.value,
    occupation: occupation.value,
    students: students.value,
    id: id.value
}

fetch('../scripts/partners_application', {
    method: 'POST', headers: {'Content-Type': 'application/json',},
    body: JSON.stringify(data)
    }).then((response) => response.json()).then((data) => {
        if (data["success"]){
            error_message.style = "color:green;"
            error_message.innerHTML = "<i class='fa-solid fa-check'></i> Successfully sent, we will be in touch with you soon."
        }
    }).catch((error) => {
        console.error('Error:', error);
        error_message.style = "color:red"
        error_message.textContent = "Error occured, please try again later or contact us."
});

PHP Side:

$first_name = $data["first_name"];
$last_name = $data["last_name"];
$email = $data["email"];
$company = $data["company"];
$occupation = $data["occupation"];
$id = $data["id"];
$students = $data["students"];

$sql = "INSERT INTO partner_applications (first_name,last_name,email,company,occupation,id,students,date_created) VALUES(?,?,?,?,?,?,?,?)";
$stmt = $conn->prepare($sql);

$stmt->bind_param("sssssbss", $first_name, $last_name, $email,$company,$occupation,$id,$students,date("Y/m/d/H:i:s"));
$stmt->execute();

$response = array("success"=>true,"id"=>$id);
echo json_encode($response);

CodePudding user response:

It is generally not recommended to store image blobs (binary large objects) directly in a database, as databases are not optimized for handling large binary files. Instead, it is better to store the image on a file system and store the path or URL to the image in the database. This allows the database to remain small and performant, while still allowing the images to be easily accessed and retrieved.

To upload an image from JavaScript to a PHP script, you can use the XMLHttpRequest object to send a POST request to the PHP script. The image data can be included in the request as a FormData object.

Here is an example of how you might upload an image using JavaScript:

   // Get the input element where the user selected the image
    var input = document.getElementById("image-input");

    // Create a new FormData object
    var formData = new FormData();

    // Add the selected image to the FormData object
    formData.append("image", input.files[0]);

    // Create a new XMLHttpRequest object
    var xhr = new XMLHttpRequest();

    // Open the request and set the method to POST
    xhr.open("POST", "upload.php");

    // Send the FormData object as the request body
    xhr.send(formData);

In the PHP script, you can access the image data using the $_FILES array and save the image to the server using the move_uploaded_file() function.

<?php
    $target_dir = "images/";
    $target_file = $target_dir . basename($_FILES["image"]["name"]);
    move_uploaded_file($_FILES["image"]["tmp_name"], $target_file);
?>

Please note that you should have to set the enctype of the form to "multipart/form-data" for the form to be able to handle files, Also you should validate the uploaded file type, size and other validation that might be needed.

  • Related