首页 > 解决方案 > tp如何删除上传的文件PHP ajax

问题描述

我想在单击提交按钮或重新加载页面后删除上传的文件。

我做了这个拖放区来拖放文件:

     <div id="drop_file_zone" class="centered" ondrop="upload_file(event)" ondragover="return false">
        <div id="drag_upload_file" class="centered">
           <p><strong>Drop file here</strong></p>
           <p>or</p>
           <p>
              <input class="btn btn-danger btn-sm" id="selectfile3" type="button" value="Select File" onclick="file_explorer();" />
           </p>
           <input type="file" id="selectfile"/>
           <div class="img-content" style="text-align: center;"></div>
        </div>
     </div>

在我的 drag_drop.js 文件中:

var fileobj;
function upload_file(e) {
   e.preventDefault();
   fileobj = e.dataTransfer.files[0];
   ajax_file_upload(fileobj);
}

function file_explorer() {
   document.getElementById('selectfile').click();
   document.getElementById('selectfile').onchange = function () {
      fileobj = document.getElementById('selectfile').files[0];
      ajax_file_upload(fileobj);
   };
}

function ajax_file_upload(file_obj) {
   if (file_obj != undefined) {
      var form_data = new FormData();
      form_data.append('file', file_obj);
      var xhttp = new XMLHttpRequest();
      xhttp.open("POST", "/app/helpers/upload_file.php", true);
      xhttp.onload = function (event) {
         oOutput = document.querySelector('.img-content');
         if (xhttp.status == 200) {
            if(this.responseText == 'false'){
               console.log('no type');
            } else {
               oOutput.innerHTML = "<img src='/app/assets/img/pdf.png' alt='The Image' width='32' height='32'/><p>" + this.responseText + "</p>";
            }
         } else {
            oOutput.innerHTML = "Error " + xhttp.status + " occurred when trying to upload your file.";
         }
      }

      xhttp.send(form_data);
   }
}

在upload_file.php这个函数上:

<?php
$arr_file_types = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];

if (!(in_array($_FILES['file']['type'], $arr_file_types))) {
   echo "false";
   return;
}

if (!file_exists('uploads')) {
   mkdir('uploads', 0777);
}

$filename = $_FILES['file']['name'];

move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $filename);


echo $filename;
die;

但是当我按下按钮(此按钮会将文档保存在数据库中)或重新加载页面时,我真的不知道如何删除这些临时文档。

标签: javascriptphphtmljqueryajax

解决方案


推荐阅读