使用jQuery上传照片只需重新加载页面而不是运行该功能

时间:2018-04-05 17:47:17

标签: php jquery forms

我正在尝试制作一个弹出窗体,利用jQuery和PHP将照片上传到服务器并创建关于照片的数据库条目。

想要什么:
- 用户上传照片。除了.jpg / .jpeg之外的任何其他内容都将被拒绝 -Photo调整为1000x1000和250x250。原始文件被销毁 - 照片和拇指被发送到各自的文件夹(上传和上传/拇指) -Mysql声明数据库中的新文件,包括标题,描述,时间。

它只是重新加载页面。到目前为止,这是我的代码。大多数PHP代码都需要使用(图像编辑部分)

HTML

<div class="popup popup2 flex-enable" data-popup="popup-2">
            <div class="popup-inner flex-center">
                <h2 class="small-white-title textcenter">Upload a photo</h2>
                <hr>
                <div class="flex-enable">
                    <form class="flex-enable flex-column flex-center" id="uploadForm" action="" method="post" enctype="multipart/form-data">
                    <div class="small-white-subtitle form-label flex-column flex-center textcenter">
                        <label for="title">Τίτλος Φωτογραφίας</label>
                        <input class="form-input-large small-white-title" type="text" id="phototitle" name="title" placeholder="Γράψτε εδώ τον τίτλο...">
                    </div>
                    <div class="small-white-subtitle form-label flex-column flex-center">
                        <input type="file" name="file" id="file" class="inputfile" />
                        <label id="uploadPhoto" for="file">Επιλέξτε αρχείο<br></label>
                        <div id="message"></div>
                    </div>
                    <br>
                    <div class="small-white-subtitle form-label flex-column flex-center textcenter">
                        <label for="description">Περιγραφή Φωτογραφίας</label>
                        <input class="form-input-large small-white-title" type="text" id="photodesc" name="photodesc" placeholder="Γράψτε εδώ μία περιγραφή...">
                    </div>

                    <input type="submit" value="Upload" >
                    <input type="reset" value="Reset" >
                    </form>
                </div>
                <a class="popup-close" data-popup-close="popup-2" href="#">×</a>
            </div>
        </div>

JQ

$(function(){
    $(document).on('drop dragover',function(e){
        e.preventDefault();
    });
    $('input[type=file]').on('change',anevase);
});

function anevase(event){
    $sanitizedFilename = event.target.value.replace("C:\\fakepath\\","");
    $("#uploadPhoto").html($sanitizedFilename);
    file = event.target.files[0];
    var data = new FormData();
    if (!file.type.match('image/jpg') || !file.type.match('image/jpeg')){
        $("uploadPhoto").html("Please select a jpg file");
    }
    else if(file.size>5000000){
        $("uploadPhoto").html("Please select a smaller file (<5 MB)");
    }
    else{
        data.append('file', file, file.name);
        var xhr = new XMLHTTPRequest();
        xhr.open('POST', 'upload.php', true);
        xhr.send(data);
        xhr.onload = function(){
            var response = JSON.parse(xhr.responseText);
            if(xhr.status === 200 && response.status == 'ok'){
                $("#uploadPhoto").html("File has been uploaded successfully.")
            }
            else if(response.status == 'type_err'){
                $("#uploadPhoto").html("Please choose an images file. Click to upload another.");
            }
            else{
                $("#uploadPhoto").html("Some problem occured, please try again.");
            }
        };
    }
}

PHP

<?php
require('connect.php');

function makeImage($imgfile, $imgname, $inputWidth, $inputHeight, $path){

    $saving_path = $path."/".$imgname;
    $source = imagecreatefromjpeg($imgfile);    
    $size= getimagesize($imgfile);
    $width = $size[0];
    $height = $size[1];

    $finalWidth=$inputWidth;
    $finalHeight=$inputHeight;

    if ($width>$height){
        $resizeFactor=$finalWidth/$width;

    }
    else{
        $resizeFactor=$finalHeight/$height; 
    }

    $finalWidth=$width*$resizeFactor;
    $finalHeight=$height*$resizeFactor;

    $thumb = imagecreatetruecolor($finalWidth, $finalHeight);   
    imagecopyresampled($thumb, $source, 0, 0, 0, 0, $finalWidth, $finalHeight, $width, $height);    
    imagejpeg($thumb, $saving_path, 90);
}

if(isset($_POST) == true){
    $fileName = uniqid("p_");
    $title=mysqli_real_escape_string($conn, $_POST['title']);
    $description=mysqli_real_escape_string($conn, $_POST['photodesc']);
    $targetDir = "uploads/";
    $thumbDir = "uploads/thumbs/";
    $targetFile = $targetDir.$fileName;
    $fileExt = pathinfo($targetFile, PATHINFO_EXTENSION);
    $allowExt = array('jpg','jpeg');

    if(in_array($fileExt, $allowExt){
        makeImage($_FILES['file'], $filename.".jpg", 1000, 1000, $targetDir);
        makeImage($_FILES['file'], $filename.".jpg", 250, 250, $thumbsDir);
        unlink($image['tmp_name']) or die('Warning! Original file could not be deleted!');
        $insertPhotoQuery="INSERT INTO photos (filename, title, description, timestamp) VALUES ('$fileName', '$title', '$description', now())";
        $insertPhotoStatement = mysqli_prepare($conn, $insertPhotoQuery);
        if(mysqli_stmt_execute($insertPhotoStatement)){
            $response['status'] = 'ok';
        }
        else{
            $response['status'] = 'err';
        }
    }
    else{
        $response['status'] = 'type_err';
    }
    echo json_encode($response);
}
?>

1 个答案:

答案 0 :(得分:0)

您没有取消表单操作,因此页面会自动重新加载(您有一个空action属性,该属性转换为“在提交时,将表单数据发送到当前页面”。

要取消活动,请在anevase功能中添加以下内容,例如在它开始时:

event.preventDefault();