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

时间:2019-04-09 08:52:33

标签: jquery

我试图通过两列var x = ("00" + 9).slice(-2); name将图像添加到我的数据库中。但是,当我尝试下面的代码时,只会插入id,而不会插入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">

2 个答案:

答案 0 :(得分:1)

在遵循我的代码之前,将mysql中的image字段设置为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);
?>

答案 1 :(得分:1)

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