图片上传后页面刷新

时间:2019-11-13 09:18:00

标签: php jquery

上传图像后,页面会刷新,我不确定如何阻止这种情况的发生。我确实有e.preventDefault()

我知道这可能与这一行有关

if(in_array($ext, $allowed) && move_uploaded_file($temp, 'uploads/'.$name))

这是我的代码

$(document).ready(function(){
    var dropZone = document.getElementById('drop-zone');

    $(".upload-area").on('drop', function(e){
        e.preventDefault();

        var files_list = e.originalEvent.dataTransfer.files;
        var formData  = new FormData(); 

        for(i = 0; i < files_list.length; i++){
            formData.append('file[]', files_list[i]);
        }

        uploadData(formData);


        dropZone.ondragover = function(e){
            return false;
        }

        dropZone.ondragleave = function(e){
            return false;
        }
});

function uploadData(formdata){

    $.ajax({
        url: 'upload.php',
        type: 'post',
        data: formdata,
        contentType: false,
        processData: false,
        dataType: 'json',
        success: function(response){
            addThumbnail(response);
        }
    });
}

function addThumbnail(data){
    var len = $("#uploadfile div.thumbnail").length;

    var num = Number(len);
    num = num + 1;
    var src = data.src;

    // console.log(len);
    $("#thumbnail_"+num).append('<img src="'+src+'" width="100%" height="78%">');
}

我的upload.php

$allowed = ['png', 'jpg'];

foreach($_FILES['file']['name'] as $key => $name)
{
    $temp = $_FILES['file']['tmp_name'][$key];

    $ext = explode('.', $name);
    $ext = strtolower(end($ext));

    if(in_array($ext, $allowed) && move_uploaded_file($temp, 'uploads/'.$name))
    {
        $return_arr = array("name" => $filename,"size" => $filesize);
    }
    echo json_encode($return_arr);

}

我的index.php

<form action="" method="post" enctype="multipart/form-data">
  <input type="file" name="files[]" id="file" multiple>

  <!-- Drag and Drop container-->
  <div class="upload-area"  id="drop-zone">
    <h1>Drag and Drop file here<br/>Or<br/>Click to select file</h1>
  </div>
</form>

1 个答案:

答案 0 :(得分:0)

以隐藏格式放置提交按钮。请按照以下步骤操作。

在HTML中,

document.getElementById('close')
    .addEventListener('click', function closeBox() {
        this.closest("h3").style.display='none';
    });

在Java语言中,

<input type="submit" id="submitBtn" style="display:none;">