需要修复文件上传后停止页面重新加载的问题

时间:2017-08-01 22:56:36

标签: php jquery ajax html5

我试图在没有页面刷新的情况下将文件上传到服务器。上传工作但上传完成后页面重新加载,这不是我想要的。我正在重定向到iframe(" myFrame")以停止重新加载页面,但看起来这并没有正常工作。我做错了什么?

HTML

<form id="upload" target="myFrame" action="sql/main-pix-upload.php" method="post" enctype="multipart/form-data">
  <input id="main-pix" class="hidden" name="main_pix" type="file" onchange="uploadPix()" accept="image/*"/>
  <label class="gi gi-camera mb-0 text-white" for="main-pix" type="button" title="Change Picture"></label>
</form>
<iframe class="hidden" name="myFrame"></iframe>

SCRIPT

function uploadPix(){
  var form = document.getElementById('upload');
  form.onsubmit = function(e){
    e.preventDefault()
    var formData = new FormData(this);
    $.ajax({
      url: 'sql/main-pix-upload.php',
      type: 'POST',
      data: formData,
      async: false,
      cache: false,
      contentType: false,
      processData: false
    })
  });
};

PHP

$account = $_SESSION['account'];
$order = $_SESSION['order'];
$id = $_SESSION['id'];

$pathPix = ('../accounts/'.$account.'/'.$order.'/pix/'.$id.'/');
if(!is_dir($pathPix)){
  mkdir($pathPix, 0777, true);
}

$file_name = $_FILES['main_pix']['name'];
$file_size = $_FILES['main_pix']['size'];
$extension = pathinfo($file_name, PATHINFO_EXTENSION);
$new_name = "main-pix.png";
$temp = ($_FILES["main_pix"]["tmp_name"]);
$target_file = ($pathPix.$new_name);

if(0 < $_FILES['main_pix']['error']){
  echo 'Error: ' . $_FILES['main_pix']['error'] . '<br>';
}else{
  move_uploaded_file($temp, $target_file);
}

1 个答案:

答案 0 :(得分:2)

使用:

form.onsubmit = function(e) {
  e.preventDefault()
};

或:

form.addEventListener("submit", function(e) {
  e.preventDefault();
});

然后你必须使用AJAX自己进行HTTP调用。