Search code examples
javascriptphphtmlasync-awaitmultipartform-data

Undefined array key in Form Data


I am trying to upload an image using form Data. But the name of the form field server expects is not recognizable.

Warning: Undefined array key "photo"

Below is my code:

index.html

html>
<head>
 <script type = "text/javascript" src="index.js"></script>
</head>
<body>
<button onclick="uploadImage()">upload an Image</button>
</body>
</html>

index.js

async function uploadImage(){
    const data = new FormData()
    data.append('photo',{
        name: 'timg', 
        type: 'image/jpeg', 
        uri: 'C:\Users\mea\Downloads\testimg.jpeg'
    })
    return await fetch('upload_image.php',{
        method: 'POST',
        body: data,
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })
}

upload_image.php

<?php
    header('Access-Control-Allow-Origin: *');
    $target_dir = "../../images";
    $target_file = $target_dir .'/'.basename($_FILES['photo']['name']);
    $name = $_FILES['photo']['name'];
      if(move_uploaded_file($_FILES['photo']['tmp_name'], $target_file)) {
        echo json_encode (
        array('message' => 'Image uploaded Successfully'));}
    else{
        echo json_encode (
        array('message' => 'Upload failed!'));
    }
?>

I have tried all the available solutions but can not yet find the cause.


Solution

  • There is an issue in approach. $_FILE will return empty since this is not an file upload from HTML form. I have created a better approach that you may try.

    index.html

    <html>
    <head>
    </head>
    <body>
        <button onclick="uploadImage()">Upload</button>
    <script type = "text/javascript">
        async function uploadImage(){
            image_url = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
            var formData = new FormData();
            formData.append("image_url", image_url);
            formData.append("image_name", "googlelogo");
            formData.append("image_type", "png");
            
            var request = new XMLHttpRequest();
            request.open("POST", "/upload_image.php");
            request.send(formData);
            console.log(request.responseText);
        }
    </script>
    
    </body>
    </html>
    

    upload_image.php

    <?php
    try {
        $image_url = $_POST['image_url'];
        $image_name = $_POST['image_name'];
        $image_type = $_POST['image_type'];
    
        $target_dir = "uploads/";
        $target_file = $target_dir . $image_name . "." . $image_type;
        // save image to uploads folder
        file_put_contents($target_file, file_get_contents($image_url));
        echo "Image uploaded successfully";
    } catch (Exception $e) {
        echo 'Caught exception: ',  $e->getMessage(), "\n";
    }
    ?>
    

    And always use try catch statement to find the error. The try statement allows you to define a block of code to be tested for errors while it is being executed.