ajax-php-mysqli上传图像

f4t66c6m  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(283)

使用ajax在数据库中上传图片url,但提交表单时出错。我想上传图片的网址im数据库没有页面刷新。错误是gethttps://api.ciuvo.com/api/analyze?url=http%3a%2f%2flocalhost%2f&version=2.1.3&tag=threesixty&uuid=c473346a-075c-48cd-a961-f4b68efe2c4f 400(错误请求)


**html code**

<form id="form" enctype="multipart/form-data">
<label>Image:</label>
<input type="file" name="txtimg">
<input type="submit" value="INSERT IMAGE" name="btnimage">
</form>
<div id="message"></div>

**ajax request**

<script type="text/javascript">
$(document).ready(function (e) {
$("#form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
  url: "upload.php",   
  type: "POST",             
  data:  new FormData(this),   
  contentType: false,          
      cache: false,         
  processData:false,        
  success: function(data)     
    {
      $("#message").html(data);     
    }         
 });
 }));
 });

PHP代码

<?php
$host="localhost";
$user="root";
$pass="";
$db="test";
$con=mysqli_connect($host,$user,$pass);
mysqli_select_db($con,$db);
if (isset($_FILES["file"]["type"])) {
$dir = "images/";
$imagelocation=$dir.basename($_FILES['txtimg']['name']);
$extension = pathinfo($imagelocation,PATHINFO_EXTENSION);
if($extension != 'jpg' && $extension != 'png' && $extension != 'jpeg')
{
    echo"plzz upload only jpg,jpeg And png";
}
else
{
    if(move_uploaded_file($_FILES['txtimg']['tmp_name'],$imagelocation) )

    {
        if(mysqli_query($con,"Insert into img (img_url) values($imagelocation')"))
        {
            echo"SUCCESSFULLY";
        }
    }

        else {

            echo"ERROR";

        }
}

}

?>
y3bcpkx1

y3bcpkx11#

不应该在ajax请求中调用formdata对象,
html代码

<form id="form" enctype="multipart/form-data">
<label>Image:</label>
<input type="file" name="txtimg">
<input type="submit" value="INSERT IMAGE" name="btnimage">
</form>
<div id="message"></div>

**ajax request**

<script type="text/javascript">
$(document).ready(function (e) {

$("#form").on('submit',(function(e) {
e.preventDefault();

var fdata = new FormData(this);

$.ajax({
  url: "upload.php",   
  type: "POST",             
  data: fdata,   
  contentType: false,          
      cache: false,         
  processData:false,        
  success: function(data)     
    {
      $("#message").html(data);     
    }         
 });
 }));
 });

相关问题