Home > Software design >  Upload an image from input type file to a server
Upload an image from input type file to a server

Time:05-27

I am struggling to upload a file to MySQL, what is wrong here? Cannot figure it out for 3 hours, but it should be relatively simple...

HTML:

 <form>
 <input  type="file" accept="image/jpg" id="pic_in_in" required>
 <button  onclick="create_band()">Upload</button>
 </form>

JS:

function create_band() {
console.log("ADDED");

    let obj = {
        image : $('input[type=file]').val()

    };

    $.ajax({
        type: "POST",
        url: "db/addBand.php",
        data: obj,
        success: function (res) {
            loadBandsData();
            $('#pic_in_in').val("");

        }
    });
 }

PHP:

<?php

$image = $_FILES["image"]["tmp_name"];


    $dbc = mysqli_connect('localhost', 'root', '', 'va_final_project');
    $query = "INSERT INTO va_band_name (band_img) VALUES '$image'
                
    $data = mysqli_query($dbc, $query);
   mysqli_close($dbc);
?>

CodePudding user response:

Have you tried adding the enctype atribute to your form?

<form action="upload.php" method="post" enctype="multipart/form-data">
  Select image to upload:
  <input type="file" name="fileToUpload" id="fileToUpload">
  <input type="submit" value="Upload Image" name="submit">
</form>

This is code from w3schools.com, best of luck and hope it helps

CodePudding user response:

To upload file thru ajax, use FormData, and to store data of image into a db table (say in a LONGBLOB field), you may use fread and send_long_data to do the job.

Please find below the code (including one to let you view the uploaded photos):

HTML

<script
  src="https://code.jquery.com/jquery-3.6.0.js"
  integrity="sha256-H K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
  crossorigin="anonymous"></script>

<form>
 <input  type="file" accept="image/jpg" id="pic_in_in" required>
 <button  onclick="create_band()">Upload</button>
</form>

<script>

function create_band() {
//console.log("ADDED");

  var file_data = $('#pic_in_in').prop('files')[0];   
    var form_data = new FormData();                  
    form_data.append('file', file_data);
   
    $.ajax({
        async:false,
        url: 'addBand.php', // <-- point to server-side PHP script 
        dataType: 'text',  // <-- what to expect back from the PHP script, if anything
        contentType: false,
        processData: false,
        data: form_data,                         
        type: 'post',
        success: function(php_script_response){
            alert(php_script_response); // <-- display response from the PHP script, if any
        }
     });

}
 </script>

PHP (addBand.php)

<?php

ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);

$servername = "localhost";
$username = "xxxxxxx";
$password = "xxxxxxx";
$dbname = "xxxxxxx";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    $tmpName = $_FILES['file']['tmp_name'];

  // Read the file 
  $fp      = fopen($tmpName, 'r');
  $image = fread($fp, filesize($tmpName));
  fclose($fp);

    $sql = "INSERT INTO va_band_name (band_img) VALUES (?)";

   $statement = $conn->prepare($sql);
   $null = NULL; 

   $statement->bind_param('b', $null);
   $statement->send_long_data(0, $image); 
   $statement->execute();
   
 $check = mysqli_stmt_affected_rows($statement);

 if($check == 1){
   $res = 'Image was uploaded';
 }else{
   $res = 'Something went wrong!';
 }
echo $res; 
}
?>

PHP (view uploaded photos):

Uploaded photos (if any):
<br>

<?php

$servername = "localhost";
$username = "xxxxxxx";
$password = "xxxxxxx";
$dbname = "xxxxxxx";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

$sql = "SELECT * FROM va_band_name";
$statement = $conn->prepare($sql);
$statement->execute();
$result = $statement->get_result();

foreach($result as $row){

echo '<img src="data:image/jpg;base64,'.base64_encode($row['band_img']).'" width="200" height=auto/>';
echo "<hr>";
}

?>
  •  Tags:  
  • php
  • Related