简体   繁体   English

我使用jquery上传的图片无法正常工作

[英]my image upload using jquery is not working

I am trying to upload an image using Jquery and php but it's not getting uploaded. 我正在尝试使用Jquery和php上传图片,但没有上传图片。 Anybody who knows how to fix this please help me solve this. 知道如何解决此问题的任何人请帮助我解决此问题。 I checked the ajax url on console.url and it was working but i don't know why its not getting uploaded. 我在console.url上检查了ajax url,它正在工作,但是我不知道为什么它没有被上传。

index.php : index.php

<form enctype="multipart/form-data" name="imageform"  id="imageform" method="post">
    <div class="form-group">
        <label>Please Choose Image: </label>
        <input class='file' type="file" class="form-control" name="images" id="images" placeholder="Please choose your image">
        <span class="help-block"></span>
    </div>
    <div id="loader" style="display: none;">Please wait image uploading to server....
    </div>
    <input type="submit" value="Upload" name="image_upload" id="image_upload" class="btn"/>
</form>

script: 脚本:

$(document).ready(function(){
   $('#imageform').on('click', function() {
       var form = $('imageform')[0]; // You need to use standard javascript object here
       var formData = new FormData(form);
       $.ajax({
           url:         'ajax.php',
           data:        formData,
           cache:       false,
           contentType: false,
           processData: false,
           type:        'POST',
           success:     function (data) {
           //   alert(data);
        }
       });
     });
   });

ajax.php: ajax.php:

<?php
require_once 'dbconnect.php';
$data = array();
if (isset($_POST['image_upload'] ) && !empty($_FILES['images'])) {

    $image = $_FILES['images'];
    $allowedExts = array("gif", "jpeg", "jpg", "png");

    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }

    // Create directory if not exists.
    if (!file_exists('images')) {    
        mkdir('images', 0777, true);
    }
    $image_name = $image['name'];

    // Get image extension.
    $ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));

    // Assign unique name to image.
    $name = time() . '.' . $ext;
    //$name = $image_name;
    //image size calcuation in KB
    $image_size = $image['size'] / 1024;
    $image_flag = true;

    // Max image size.
    $max_size = 512;
    if (in_array($ext, $allowedExts) && $image_size < $max_size) {
        $image_flag = true;
    } else {
        $image_flag = false;
        $data['error'] = "Maybe $image_name exceeds max $max_size KB size or incorrect file extension";
    } 

    if ($image["error"] > 0) {
        $image_flag = false;
        $data['error']  = '';
        $data['error'] .= '<br/> ' . $image_name . ' Image contains error - Error Code : ' . $image['error'];
    }

    if ($image_flag) {
        $files = glob('images/*'); // get all file names
        foreach($files as $file) { // iterate files
            if(is_file($file)) {
                unlink($file); // delete file
            }
        }
        move_uploaded_file($image['tmp_name'], 'images/' . $name);

        $src             = 'images/' . $name;
        $dist            = 'images/thumbnail_' . $name;
        $data['success'] = $thumbnail = 'thumbnail_' . $name;
        thumbnail($src, $dist, 200);
        $sql1 = "TRUNCATE TABLE images";
        if (!mysqli_query($conn,$sql1)) {
            die('Error: ' . mysqli_error($conn));
        } 
        $sql2 = "TRUNCATE TABLE image_tag";
        if (!mysqli_query($conn,$sql2)) {
            die('Error: ' . mysqli_error($conn));
        } 

        $sql = "INSERT INTO images (`id`, `original_image`, `thumbnail_image`, `ip_address`) VALUES (NULL, '$name', '$thumbnail', '$ip');";
        if (!mysqli_query($conn,$sql)) {
            die('Error: ' . mysqli_error($conn));
        }
    }
    mysqli_close($conn);
    echo json_encode($data);
} else {
    $data[] = 'No Image Selected..';
}

function thumbnail ($src, $dist, $dis_width = 100) {
    $img       = '';
    $extension = strtolower(strrchr($src, '.'));
    switch($extension)
    {
        case '.jpg':
        case '.jpeg':
            $img = @imagecreatefromjpeg($src);
            break;
        case '.gif':
            $img = @imagecreatefromgif($src);
            break;
        case '.png':
            $img = @imagecreatefrompng($src);
            break;
    }
    $width  = imagesx($img);
    $height = imagesy($img);

    $dis_height = $dis_width * ($height / $width);

    $new_image = imagecreatetruecolor($dis_width, $dis_height);
    imagecopyresampled($new_image, $img, 0, 0, 0, 0, $dis_width, $dis_height, $width, $height);

    $imageQuality = 100;

    switch($extension)
    {
        case '.jpg':
        case '.jpeg':
            if (imagetypes() & IMG_JPG) {
                imagejpeg($new_image, $dist, $imageQuality);
            }
            break;

        case '.gif':
            if (imagetypes() & IMG_GIF) {
                imagegif($new_image, $dist);
            }
            break;

        case '.png':
            $scaleQuality       = round(($imageQuality/100) * 9);
            $invertScaleQuality = 9 - $scaleQuality;

            if (imagetypes() & IMG_PNG) {
                imagepng($new_image, $dist, $invertScaleQuality);
            }
            break;
    }
    imagedestroy($new_image);
}

You need to use e.preventDefault() to avoid form to submit and reloading the page 您需要使用e.preventDefault()来避免表单提交和重新加载页面

Try this: 尝试这个:

$(document).ready(function(){
    $('#imageform').on('submit', function(e) {
        e.preventDefault();//preventing page to reload on submit
       var form = new FormData($('#imageform')[0]); //Form object to post using ajax

       $.ajax({
           url: 'ajax.php',
           data: form,
           cache: false,
           dataType: "JSON",
           contentType: false,
           processData: false,
           type: 'POST',

           success: function (data) {
               alert(data);
           }
       });

    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM