【问题标题】:How to add image to database using AJAX and PHP如何使用 AJAX 和 PHP 将图像添加到数据库
【发布时间】:2019-04-09 08:52:33
【问题描述】:

我正在尝试将图像添加到我的数据库中,其中包含 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);
  }
?>

【问题讨论】:

  • 我在 ajax 中将参数 method 更改为 type:"post"
  • 首先,在AJAX请求中发送二进制数据时,需要使用FormData对象,如this,并且需要将contentTypeprocessData设置为false。其次,由于image 是二进制数据,您需要将其作为 BLOB 存储在 mySql 数据库中,或者将其转换为 base64 并将其保存为字符串。最后,永远不要在 AJAX 请求中使用 async: false,这是非常糟糕的做法。
  • 要么转换为base64,要么将文件保存到目录并添加数据库路径
  • 你已经可以在网上找到很多这个过程的工作示例
  • 避免在数据库中将图像存储为 blob,这可能会降低查询执行速度,请尝试将其存储在文件夹中

标签: jquery


【解决方案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);
?>

【讨论】:

    【解决方案2】:

    您想在 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... ]
                }
            });
          });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      • 2021-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多