如何使用AJAX和PHP将图像添加到数据库

问题描述 投票:2回答:2

我正在尝试使用两列nameid将图像添加到我的数据库中。然而,当我尝试下面的代码时,只插入了id而不是image。请告诉我在哪里需要更正代码。

$(function() {
  $('#insert').click(function() {
    var file = $('#image').val();
    $.ajax({
      url: "addimg.php",
      method: "post",
      async: false,
      data: {
        "insert": 1,
        file: file
      },
      success: function(data) {
        $('#image').val('');
      }
    })
  });
});
<input type="file" name="myfile" id="image">
<input type="submit" name="insert" id="insert">
<?php
  $conn = mysqli_connect('*****', '****', '*****', '*****');
  if (isset($_POST['insert']))
  {
    $file = addslashes(file_get_contents($_FILES["myfile"]["tmp_name"]));
    $query = "INSERT INTO tbl_images(name) VALUES('$file')";
    mysqli_query($conn, $query);
  }
?>
jquery
2个回答
1
投票

在关注我的代码之前,将图像字段设置为mysql中的blob,希望这有帮助,谢谢

HTML代码

<input type="file" name="myfile" id="image">
<input type="submit" name="insert" id="insert">

在Js

$(function() {
      $('#insert').click(function() {
        var file = $('#image').prop("files")[0];  
        var form_data = new FormData();  
        form_data.append("file", file)  
        form_data.append("insert", '1') 
        $.ajax({
          url: "addimg.php",
          method: "post",
          async: false,
          data:form_data,
          cache: false,
          contentType: false,
          processData: false,
          success: function(data) {
            $('#image').val('');
          }
        })
      });
    });

在Php

<?php

  if (isset($_POST['insert']))
  {
    if(isset($_FILES["file"])){

    // Find location of uploaded file
    $tmpName = $_FILES["file"]["tmp_name"];

    // Read data
    $fileHandle = fopen($tmpName, "r");
    $image = fread($fileHandle, filesize($tmpName));
    fclose($fileHandle);

    // Run query
    $db = mysqli_connect("xxxx","xxx","xxx","xxx"); 
    $query = "INSERT INTO tbl_images(name) VALUES('$image')"; 
    $qry = mysqli_query($db, $query);
  }
  }
?>

请参阅BLOB: Storing Images using PHP inside MySQL Database

/*don't store images in a database ever*/

替代解决方案,

<?php
 $path = 'path/to/folder';
 $file_name = $_FILES['file']['name'];
 $file_tmp  = $_FILES['file']['tmp_name'];
 if (file_exists($path)) {                                             
              move_uploaded_file($file_tmp,$path.$file_name);

 } else {
    mkdir($path, 0755);                              
    move_uploaded_file($file_tmp,$path.$file_name);                                            
  }
    $path = $path.$file_name;
    $db = mysqli_connect("xxxx","xxx","xxx","xxx"); 
    $query = "INSERT INTO tbl_images(name) VALUES('$path')"; //Store image path instead
    $qry = mysqli_query($db, $query);
?>

0
投票

您想在ajax中发送multipart / form-data。因此,您必须将数据作为FormData的对象发送。这将把给定表单的所有输入值(包括文件)(form_id是表单的id)发布到服务器。在服务器端,您可以在$ _POST中获取发布的数据,在$ _FILES中获取文件

$(function() {
  $('#insert').click(function() {
    var formdata = new FormData($('#form_id')[0]);
      $.ajax({
            url: "addimg.php",
            type: 'POST',
            dataType: 'json',
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            data: formdata,
            success: function (response) {
               [ Reset your form here... ]
            }
        });
      });
});
© www.soinside.com 2019 - 2024. All rights reserved.