php - 使用 JSON 的 AJAX 上传图像不起作用

标签 php jquery mysql ajax

我正在使用下面的代码将图像文件上传到我的服务器。在进行图像选择之前它运行良好。

选择图像后,它会分为两种尺寸(中和小),文件移动也起作用。但是,我没有使用 AJAX.form req 获得结果。

我还想将地址存储在 mysql 表中。

 $(document).on('change', '#image_upload_file', function(){
                                var progressBar = $('.progressBar'), bar = $('.progressBar .bar'), percent = $('.progressBar .percent');
                                       $('#update_dp').ajaxForm({
                                                url:'/auth/ajax/update_dp',
                                                dataType: 'json',
                                                beforeSend: function() {
                                                progressBar.fadeIn();
                                                var percentVal = '0%';
                                                bar.width(percentVal)
                                                console.log(percentVal);
                                                                        },
                                                uploadProgress: function(event, position, total, percentComplete) {
                                                var percentVal = percentComplete + '%';
                                                bar.width(percentVal)
                                                console.log(percentVal);
                                                                },
                                                success: function(html, statusText, xhr, $form) {
                                                   obj = $.parseJSON(html);
                                                   console.log(html);
                                                    if(obj.status){
                                                            var percentVal = '100%';
                                                            bar.width(percentVal)
                                                            console.log(obj.image_medium);
                                                            $("#profile_dp>img").prop('src',obj.image_medium);
                                                                    }
                                                                        else {
                                                                                alert(obj.error);
                                                                            }
                                                                                },
                                                            complete: function(xhr) {
                                                             progressBar.fadeOut();
                                                             }
                                                            }).submit();

                                                        });
 .progressBar {
  background: none repeat scroll 0 0 #E0E0E0;
  left: 0;
  padding:0px;
  margin-top:3px;
  position: relative;
  margin-bottom: 3px;
  width: 100%;
  display: none;
 }
 .progressBar .bar {
  background-color: #2FAF84;
  width: 0%;
  height: 4px;
 }
 .progressBar .percent {
  display: inline-block;
  left: 0;
  text-align: center;
  top: 2px;
  width: 100%;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php

function createDir($path){
    if (!file_exists($path)) {
        $old_mask = umask(0);
        mkdir($path, 0777, TRUE);
        umask($old_mask);
    }
}

function createThumb($path1, $path2, $file_type, $new_w, $new_h, $squareSize = ''){
    /* read the source image */$source_image = FALSE;

    if (preg_match("/jpg|JPG|jpeg|JPEG/", $file_type)) {
        $source_image = imagecreatefromjpeg($path1);
    }
    elseif (preg_match("/png|PNG/", $file_type)) {

        if (!$source_image = @imagecreatefrompng($path1)) {
            $source_image = imagecreatefromjpeg($path1);
        }
    }
    elseif (preg_match("/gif|GIF/", $file_type)) {
        $source_image = imagecreatefromgif($path1);
    }
    if ($source_image == FALSE) {
        $source_image = imagecreatefromjpeg($path1);
    }

    $orig_w = imageSX($source_image);
    $orig_h = imageSY($source_image);

    if ($orig_w < $new_w && $orig_h < $new_h) {
        $desired_width = $orig_w;
        $desired_height = $orig_h;
    } else {
        $scale = min($new_w / $orig_w, $new_h / $orig_h);
        $desired_width = ceil($scale * $orig_w);
        $desired_height = ceil($scale * $orig_h);
    }

    if ($squareSize != '') {
        $desired_width = $desired_height = $squareSize;
    }

           $virtual_image = imagecreatetruecolor($desired_width, $desired_height);
// for PNG background white-----------
    $kek = imagecolorallocate($virtual_image, 255, 255, 255);
    imagefill($virtual_image, 0, 0, $kek);

    if ($squareSize == '') {
        /* copy source image at a resized size */imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $orig_w, $orig_h);
    } else {
        $wm = $orig_w / $squareSize;
        $hm = $orig_h / $squareSize;
        $h_height = $squareSize / 2;
        $w_height = $squareSize / 2;

        if ($orig_w > $orig_h) {
            $adjusted_width = $orig_w / $hm;
            $half_width = $adjusted_width / 2;
            $int_width = $half_width - $w_height;
            imagecopyresampled($virtual_image, $source_image, -$int_width, 0, 0, 0, $adjusted_width, $squareSize, $orig_w, $orig_h);
        }

        elseif (($orig_w <= $orig_h)) {
            $adjusted_height = $orig_h / $wm;
            $half_height = $adjusted_height / 2;
            imagecopyresampled($virtual_image, $source_image, 0,0, 0, 0, $squareSize, $adjusted_height, $orig_w, $orig_h);
        } else {
            imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $squareSize, $squareSize, $orig_w, $orig_h);
        }
    }

    if (@imagejpeg($virtual_image, $path2, 90)) {
        imagedestroy($virtual_image);
        imagedestroy($source_image);
        return TRUE;
    } else {
        return FALSE;
    }
}

ini_set("memory_limit", "99M");
ini_set('post_max_size', '20M');
ini_set('max_execution_time', 600);
define('IMAGE_SMALL_DIR', '../../files/images/users/small/');
define('IMAGE_SMALL_SIZE', 50);
define('IMAGE_MEDIUM_DIR', '../../files/images/users/medium/');
define('IMAGE_MEDIUM_SIZE', 250);
/*defined settings - end*/
if(isset($_FILES['image_upload_file'])){
    $output['status']=FALSE;
    set_time_limit(0);
    $allowedImageType = array("image/gif",   "image/jpeg",   "image/pjpeg",   "image/png",   "image/x-png"  );

    if ($_FILES['image_upload_file']["error"] > 0) {
        $output['error']= "Error in File";
    }
    elseif (!in_array($_FILES['image_upload_file']["type"], $allowedImageType)) {
        $output['error']= "You can only upload JPG, PNG and GIF file";
    }
    elseif (round($_FILES['image_upload_file']["size"] / 1024) > 4096) {
        $output['error']= "You can upload file size up to 4 MB";
    } else {
        /*create directory with 777 permission if not exist - start*/createDir(IMAGE_SMALL_DIR);
        createDir(IMAGE_MEDIUM_DIR);
        /*create directory with 777 permission if not exist - end*/$path[0] = $_FILES['image_upload_file']['tmp_name'];
        $file = pathinfo($_FILES['image_upload_file']['name']);
        $fileType = $file["extension"];
        $desiredExt='jpg';
        $fileNameNew = rand(333, 999) . time() . ".$desiredExt";
        $path[1] = IMAGE_MEDIUM_DIR . $fileNameNew;
        $path[2] = IMAGE_SMALL_DIR . $fileNameNew;

        if (createThumb($path[0], $path[1], $fileType, IMAGE_MEDIUM_SIZE, IMAGE_MEDIUM_SIZE,IMAGE_MEDIUM_SIZE)) {

            if (createThumb($path[1], $path[2],"$desiredExt", IMAGE_SMALL_SIZE, IMAGE_SMALL_SIZE,IMAGE_SMALL_SIZE)) {
                $output['status']=TRUE;
                $output['image_medium']= $path[1];
                $output['image_small']= $path[2];
            }
        }
    }
    echo json_encode($output);
}








?>





















?>

最佳答案

您可以使用 var form_data =new FormData(); 并使用 form_data 对象附加上传的文件。

form_data.append('image_upload_file', $('input[type=file]')[0].files[0]);
$.ajax({
    url: 'Your url here',
    data: formData,
    type: 'POST',
    contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
    processData: false, // NEEDED, DON'T OMIT THIS
    // ... Other options like success and etc
});

请在表单中检查您是否为上传文件添加了 enctype="multipart/form-data"

关于php - 使用 JSON 的 AJAX 上传图像不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48739294/

相关文章:

php - 无法在 Joomla docker 官方容器中更改 PHP 变量

jquery - 具有多格式 View 的MVC 3中的Ajax发布

php - MySQL 和用户身份验证 - 内部查询与查询后的有力证据?

php - Ajax选择控制PHP MySQL?

php - 关闭连接 PDO

php - PDO 返回空数组作为结果

javascript - 如何等待浏览器在卸载时发送图像请求?

jquery - 无法获取post ajax请求数据python

MySql "INSERT … ON DUPLICATE KEY UPDATE"仍在插入重复记录。我错过了什么?

php - 如何使用 Laravel 播种机中的 Faker 生成纬度、经度信息?