【问题标题】:Save file name to database and upload file to server将文件名保存到数据库并将文件上传到服务器
【发布时间】:2020-01-28 13:17:28
【问题描述】:

我有一个要修改的代码,从网上某处获得。它完全符合我的要求,即上传图像、预览、裁剪和保存。但是,在保存时,它会将自己的图像保存到数据库中,而不是将文件名保存到数据库和文件到服务器。

这里是代码

if(isset($_POST["image"]))
{
 include('database_connection.php');
 $data = $_POST["image"];
 $image_array_1 = explode(";", $data);
 $image_array_2 = explode(",", $image_array_1[1]);
 $data = base64_decode($image_array_2[1]);
 $imageName = time() . '.png';
 file_put_contents($imageName, $data);
 $image_file = addslashes(file_get_contents($imageName));
 $query = "INSERT INTO tbl_images(images) VALUES ('".$image_file."')";
 $statement = $connect->prepare($query);
 if($statement->execute())
 {
  echo 'Image save into database';
  unlink($imageName);
 }
}
<script>  
$(document).ready(function(){

 $image_crop = $('#image_demo').croppie({
    enableExif: true,
    viewport: {
      width:200,
      height:200,
      type:'square' //circle
    },
    boundary:{
      width:300,
      height:300
    }    
  });

  $('#insert_image').on('change', function(){
    var reader = new FileReader();
    reader.onload = function (event) {
      $image_crop.croppie('bind', {
        url: event.target.result
      }).then(function(){
        console.log('jQuery bind complete');
      });
    }
    reader.readAsDataURL(this.files[0]);
    $('#insertimageModal').modal('show');
  });

  $('.crop_image').click(function(event){
    $image_crop.croppie('result', {
      type: 'canvas',
      size: 'viewport'
    }).then(function(response){
      $.ajax({
        url:'insert.php',
        type:'POST',
        data:{"image":response},
        success:function(data){
          $('#insertimageModal').modal('hide');
          load_images();
          alert(data);
        }
      })
    });
  });

  load_images();

  function load_images()
  {
    $.ajax({
      url:"fetch_images.php",
      success:function(data)
      {
        $('#store_image').html(data);
      }
    })
  }

});  
</script>
<input type="file" name="insert_image" id="insert_image" accept="image/*" />

我真的很想将图像/文件名保存到数据库并将文件上传到服务器上的文件夹。 非常感谢任何有助于我实现我想要的修改。

【问题讨论】:

  • 请为此发布您的 HTML/表单,以便我们查看正在处理的内容。处理文件需要 $_FILES 超全局而不是 $_POST 以及正确的 enctype。
  • @FunkFortyNiner javascript id 处理所有前端工作,不过,让我也发布 javascript 代码

标签: javascript php mysqli file-upload


【解决方案1】:

您获取图像的方式是错误的。您必须使用$_FILES 来获取图像数据。您正在使用$_POST

【讨论】:

  • 我已经在上面的comment 中说过了。
  • 好的,让我改变一下看看结果@lalit
  • @HackZaid 好的,请检查,如果您认为正确,请接受我的回答。谢谢
  • @FunkFortyNiner 这是一个基本问题。每个人都会提出该解决方案。这并不意味着你会让别人的答案变得无用。所以,请让我的回答有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多